Search code examples
javascriptjquerycssresponsive-designonresize

How to use JavaScript OnResize with delay or less processing intensive


Im trying to write a JavaScript/jQuery function that I can use to call other functions, or set CSS/LESS based on if the user resizes a window beyond breakpoint thresholds, or if they rotate a device from landscape to portrait.

Currently I am using the following:

$(window).on('resize', function() {
// IF/Switch Case statement, check current width of window is > mobile, or tablet, or desktop
    // Do stuff depending on which size the window is at currently.
// End if/Switch case.
}

But this is not ideal, as it will inevitably put strain/delay on the user experience, as the function could literally be running loads of times while a user is dragging the window bigger and smaller.

Instead, is there a way to just fire on change of breakpoints, or maybe even running onResize every 1 or 2 seconds, or once a user has stopped dragging the window maybe?

That way, the processing intensity would be considerably less.

P.s. when I say breakpoints, I mean I have width settings for Mobile, BigMobile, Tablet, Retina Displays, Tablet.

But just simply mobile, tablet, desktop can be a compromise too.

How can I detect breakpoint changes without causing intensive processing onResize. Any tips on which direction to go with this?


Solution

  • Use a setTimeout and a clearTimeout.

    var t = null;
    
    window.onResize(function() {
       if (t!= null) clearTimeout(t);
    
       t = setTimeout(function() {
           ...
       }, 500);
    }}
    

    During the dragging the timeout is Always cleared and nothing happen. But when the user stop dragging it run the last setTimeout and will execute your code.