JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

JavascriptJquery

Javascript Problem Overview


I'm using JQuery as such:

$(window).resize(function() { ... });

However, it appears that if the person manually resizes their browser windows by dragging the window edge to make it larger/smaller, the .resize event above fires multiple times.

Question: How to I call a function AFTER the browser window resize completed (so that the event only fires once)?

Javascript Solutions


Solution 1 - Javascript

Here's a modification of CMS's solution that can be called in multiple places in your code:

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

Usage:

$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});

CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer variable.

With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.

Solution 2 - Javascript

I prefer to create an event:

$(window).bind('resizeEnd', function() {
    //do something, window hasn't changed size in 500ms
});

Here is how you create it:

 $(window).resize(function() {
        if(this.resizeTO) clearTimeout(this.resizeTO);
        this.resizeTO = setTimeout(function() {
            $(this).trigger('resizeEnd');
        }, 500);
    });

You could have this in a global javascript file somewhere.

Solution 3 - Javascript

I use the following function for delaying repeated actions, it will work for your case:

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

Usage:

$(window).resize(function() {
    delay(function(){
      alert('Resize...');
      //...
    }, 500);
});

The callback function passed to it, will execute only when the last call to delay has been made after the specified amount of time, otherwise a timer will be reset, I find this useful for other purposes like detecting when the user stopped typing, etc...

Solution 4 - Javascript

If you have Underscore.js installed, you could:

$(window).resize(_.debounce(function(){
    alert("Resized");
},500));

Solution 5 - Javascript

Some of the previously mentioned solutions did not work for me, even though they are of more general usage. Alternatively I've found this one that did the job on window resize:

$(window).bind('resize', function(e){
    window.resizeEvt;
    $(window).resize(function(){
        clearTimeout(window.resizeEvt);
        window.resizeEvt = setTimeout(function(){
        //code to do after window is resized
        }, 250);
    });
});

Solution 6 - Javascript

Many thanks to David Walsh, here is a vanilla version of underscore debounce.

Code:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

Simple usage:

var myEfficientFn = debounce(function() {
	// All the taxing stuff you do
}, 250);

$(window).on('resize', myEfficientFn);

Ref: http://davidwalsh.name/javascript-debounce-function

Solution 7 - Javascript

Actually, as I know, you can't do some actions exactly when resize is off, simply because you don't know future user's actions. But you can assume the time passed between two resize events, so if you wait a little more than this time and no resize is made, you can call your function.
Idea is that we use setTimeout and it's id in order to save or delete it. For example we know that time between two resize events is 500ms, therefore we will wait 750ms.

var a;
$(window).resize(function(){
  clearTimeout(a);
  a = setTimeout(function(){
    // call your function
  },750);
});

Solution 8 - Javascript

Declare globally delayed listener:

var resize_timeout;

$(window).on('resize orientationchange', function(){
	clearTimeout(resize_timeout);

	resize_timeout = setTimeout(function(){
		$(window).trigger('resized');
	}, 250);
});

And below use listeners to resized event as you want:

$(window).on('resized', function(){
	console.log('resized');
});

Solution 9 - Javascript

It works for me. See this solution - https://alvarotrigo.com/blog/firing-resize-event-only-once-when-resizing-is-finished/

var resizeId;
$(window).resize(function() {
    clearTimeout(resizeId);
    resizeId = setTimeout(doneResizing, 500);
});
function doneResizing(){
    //whatever we want to do 
}

Solution 10 - Javascript

Simple jQuery plugin for delayed window resize event.

SYNTAX:

Add new function to resize event

jQuery(window).resizeDelayed( func, delay, id ); // delay and id are optional

Remove the function(by declaring its ID) added earlier

jQuery(window).resizeDelayed( false, id );

Remove all functions

jQuery(window).resizeDelayed( false );

USAGE:

// ADD SOME FUNCTIONS TO RESIZE EVENT
jQuery(window).resizeDelayed( function(){ console.log( 'first event - should run after 0.4 seconds'); }, 400,  'id-first-event' );
jQuery(window).resizeDelayed( function(){ console.log('second event - should run after 1.5 seconds'); }, 1500, 'id-second-event' );
jQuery(window).resizeDelayed( function(){ console.log( 'third event - should run after 3.0 seconds'); }, 3000, 'id-third-event' );

// LETS DELETE THE SECOND ONE
jQuery(window).resizeDelayed( false, 'id-second-event' );

// LETS ADD ONE WITH AUTOGENERATED ID(THIS COULDNT BE DELETED LATER) AND DEFAULT TIMEOUT (500ms)
jQuery(window).resizeDelayed( function(){ console.log('newest event - should run after 0.5 second'); } );

// LETS CALL RESIZE EVENT MANUALLY MULTIPLE TIMES (OR YOU CAN RESIZE YOUR BROWSER WINDOW) TO SEE WHAT WILL HAPPEN
jQuery(window).resize().resize().resize().resize().resize().resize().resize();

USAGE OUTPUT:

first event - should run after 0.4 seconds
newest event - should run after 0.5 second
third event - should run after 3.0 seconds

PLUGIN:

jQuery.fn.resizeDelayed = (function(){
    
    // >>> THIS PART RUNS ONLY ONCE - RIGHT NOW
    
    var rd_funcs = [], rd_counter = 1, foreachResizeFunction = function( func ){ for( var index in rd_funcs ) { func(index); } };
    
    // REGISTER JQUERY RESIZE EVENT HANDLER
    jQuery(window).resize(function() {
        
        // SET/RESET TIMEOUT ON EACH REGISTERED FUNCTION
        foreachResizeFunction(function(index){
            
            // IF THIS FUNCTION IS MANUALLY DISABLED ( by calling jQuery(window).resizeDelayed(false, 'id') ),
            // THEN JUST CONTINUE TO NEXT ONE
            if( rd_funcs[index] === false )
                return; // CONTINUE;
            
            // IF setTimeout IS ALREADY SET, THAT MEANS THAT WE SHOULD RESET IT BECAUSE ITS CALLED BEFORE DURATION TIME EXPIRES
            if( rd_funcs[index].timeout !== false )
                clearTimeout( rd_funcs[index].timeout );
            
            // SET NEW TIMEOUT BY RESPECTING DURATION TIME
            rd_funcs[index].timeout = setTimeout( rd_funcs[index].func, rd_funcs[index].delay );
             
        });
        
    });
    
    // <<< THIS PART RUNS ONLY ONCE - RIGHT NOW
    
    // RETURN THE FUNCTION WHICH JQUERY SHOULD USE WHEN jQuery(window).resizeDelayed(...) IS CALLED
    return function( func_or_false, delay_or_id, id ){
        
        // FIRST PARAM SHOULD BE SET!
        if( typeof func_or_false == "undefined" ){
            
            console.log( 'jQuery(window).resizeDelayed(...) REQUIRES AT LEAST 1 PARAMETER!' );
            return this; // RETURN JQUERY OBJECT
            
        }
        
        // SHOULD WE DELETE THE EXISTING FUNCTION(S) INSTEAD OF CREATING A NEW ONE?
        if( func_or_false == false ){
            
            // DELETE ALL REGISTERED FUNCTIONS?
            if( typeof delay_or_id == "undefined" ){
                
                // CLEAR ALL setTimeout's FIRST
                foreachResizeFunction(function(index){
                    
                    if( typeof rd_funcs[index] != "undefined" && rd_funcs[index].timeout !== false )
                        clearTimeout( rd_funcs[index].timeout );
                
                });
                
                rd_funcs = [];
                
                return this; // RETURN JQUERY OBJECT
                
            }
            // DELETE ONLY THE FUNCTION WITH SPECIFIC ID?
            else if( typeof rd_funcs[delay_or_id] != "undefined" ){
                
                // CLEAR setTimeout FIRST
                if( rd_funcs[delay_or_id].timeout !== false )
                    clearTimeout( rd_funcs[delay_or_id].timeout );
                
                rd_funcs[delay_or_id] = false;
                
                return this; // RETURN JQUERY OBJECT
                
            }
            
        }
        
        // NOW, FIRST PARAM MUST BE THE FUNCTION
        if( typeof func_or_false != "function" )
            return this; // RETURN JQUERY OBJECT
        
        // SET THE DEFAULT DELAY TIME IF ITS NOT ALREADY SET
        if( typeof delay_or_id == "undefined" || isNaN(delay_or_id) )
            delay_or_id = 500;
        
        // SET THE DEFAULT ID IF ITS NOT ALREADY SET
        if( typeof id == "undefined" )
            id = rd_counter;
        
        // ADD NEW FUNCTION TO RESIZE EVENT
        rd_funcs[id] = {
            func : func_or_false,
            delay: delay_or_id,
            timeout : false
        };
        
        rd_counter++;
        
        return this; // RETURN JQUERY OBJECT
        
    }
    
})();

Solution 11 - Javascript

Assuming that the mouse cursor should return to the document after window resize, we can create a callback-like behavior with onmouseover event. Don't forget that this solution may not work for touch-enabled screens as expected.

var resizeTimer;
var resized = false;
$(window).resize(function() {
   clearTimeout(resizeTimer);
   resizeTimer = setTimeout(function() {
       if(!resized) {
           resized = true;
           $(document).mouseover(function() {
               resized = false;
               // do something here
               $(this).unbind("mouseover");
           })
       }
    }, 500);
});

Solution 12 - Javascript

This is what i've implemented:

$(window).resize(function(){ setTimeout(someFunction, 500); });

we can clear the setTimeout if we expect resize to happen less than 500ms

Good Luck...

Solution 13 - Javascript

Many Solutions. I tried to do the event after a mouuseevent so I addded the reload just after ouse enters the window:

jQuery(window).resize(function() {
        // this. is window
        if(  this.resizeTO) {
            clearTimeout(this.resizeTO) 
        };
    
         this.resizeTO = setTimeout(function() {
            
                jQuery(window).mouseenter(function() {
                    if( jQuery(window).width() < 700 &&   jQuery(window).width() > 400 ){
                        console.log("mouseenter  reloads elements"); 
                        // is loading the page  
                        location.reload();
                        //
                     }; // just mobile
                }); // mouse  fired    
        }, 400);  // set Time Ouuut
}); 



 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsarahView Question on Stackoverflow
Solution 1 - JavascriptbrahnView Answer on Stackoverflow
Solution 2 - JavascriptCarlos Martinez TView Answer on Stackoverflow
Solution 3 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 4 - JavascriptJT.View Answer on Stackoverflow
Solution 5 - JavascriptDusanVView Answer on Stackoverflow
Solution 6 - JavascriptIrvin DomininView Answer on Stackoverflow
Solution 7 - JavascriptnewintView Answer on Stackoverflow
Solution 8 - JavascriptgzzzView Answer on Stackoverflow
Solution 9 - Javascriptvishwajit76View Answer on Stackoverflow
Solution 10 - JavascriptDejanView Answer on Stackoverflow
Solution 11 - JavascriptonurView Answer on Stackoverflow
Solution 12 - JavascriptAakashView Answer on Stackoverflow
Solution 13 - Javascriptuser3432605View Answer on Stackoverflow