Explain Codes LogoExplain Codes Logo

Jquery: How to call RESIZE event only once it's FINISHED resizing?

javascript
debounce
event-handling
performance
Alex KataevbyAlex Kataev·Sep 5, 2024
TLDR

To ensure the resize event is triggered after the completed resizing, implement a debouncer with setTimeout:

let resizeTimer; $(window).resize(function() { // As Gerry Joe Weise would say: "Where's my timer?" clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { // Your code after the resizing concert is over console.log('The resizing has left the building!'); }, 250); // A pause as epic as John Cage's 4'33" (well, 250 milliseconds!) });

This snappy snippet applies a setTimeout delay, reset if resizing continues, to prevent multiple encores. The clearTimeout allows just a single final act. Tweak the 250 to adjust the delay.

Mastering the debounce effect

Debouncing is like an event bouncer - it only lets an event through after it's waited around long enough. It prevents the overwhelming crash of rapid-fire events that could cause nasty performance glitches.

Adjustable debounce timing

Balance response time and efficiency like a gymnast on a beam by adjusting the debounce timeout. If 250ms feels like waiting for a sloth to cross the road, reduce it. If you're drowning in resize events, increase it. Strike the right balance for your specific need.

Filtering out the noise

Interested in significant resize events and want to filter out noise like a scroll bar appearance? Here are two ways:

  1. Switch off scroll bars by manipulating document.body.style.overflow during a resize.
  2. Store and compare window dimensions before invoking your logic to ensure it only reacts to actual changes.
var lastWidth = $(window).width(), lastHeight = $(window).height(); $(window).resize(function() { var newWidth = $(window).width(), newHeight = $(window).height(); if(newWidth !== lastWidth || newHeight !== lastHeight){ lastWidth = newWidth; lastHeight = newHeight; // Resize logic here, or as I like to say, the resize renaissance! } });

Storing the resize timeout reference id

Keep the global scope clean and tidy! Use jQuery.data() to stash away our timeout references:

$(window).resize(function() { var timeout = $.data(this, 'resizeTimer'); clearTimeout(timeout); timeout = setTimeout(() => { // Handle resize like a boss }, 300); $.data(this, 'resizeTimer', timeout); });

Plug into a plugin or utility

Don't feel like reinventing the wheel? Consider using jQuery plugin extensions like Ben Alman's jQuery Throttle/Debounce or ready-to-rock functions from libraries like Underscore.js and Lodash:

$(window).resize(_.debounce(function() { // Function code here - no need to sweat the small stuff! }, 250));