JQuery - resizing a window; after

I am currently using the jQuery resize function, but due to the fact that I adjust when resizing, just too much is done to make it smooth, since it works with every adjustment.

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

Is there a way to disable the function after resizing has stopped? Like $ (window) .afterResize () or something else?

Any solutions are welcome.

+4
source share
3 answers

I'm not sure if there is a β€œclean” native way to do this (I hope there is someone to shed some light)

but you will β€œhack” it like this http://jsfiddle.net/tuuN3/

 var myInterval = false; // this variable will hold the interval and work as a flag var $win = $(window); //jquery win object var dimensions = [ $win.width(), $win.height() ]; //initial dimensions $(window).resize(function() { //on window resize... if( !myInterval ) //if the interval is not set, { myInterval = setInterval( function() { //initialize it //and check to see if the dimenions have changed or remained the same if( dimensions[ 0 ] === $win.width() && dimensions[ 1 ] === $win.height() ) { //if they are the same, then we are no longer resizing the window clearInterval( myInterval ); //deactivate the interval myInterval = false; //use it as a flag doStuff(); //call your callback function } else { dimensions[ 0 ] = $win.width(); //else keep the new dimensions dimensions[ 1 ] = $win.height(); } }, 64 ); //and perform a check every 64ms } }); 
+1
source

Set a timeout and do the action 100 ms later, maybe.

 var timer; $(window).resize(function() { clearTimeout(timer); timer = setTimeout(myFunction, 100); }); 
+7
source

You should investigate "debounce" or "throttle" as this applies to javascript. Depending on your needs, you may need to use one or the other. Here is the debounce / throttle library that I used, as well as great descriptions of their applications. There is no need to reinvent the wheel - plus it's always great to know the terminology and identify useful coding patterns (for future maintainers of your code).

+1
source

All Articles