Jquery: How to call RESIZE event only once it's FINISHED resizing?
To ensure the resize
event is triggered after the completed resizing, implement a debouncer with setTimeout
:
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:
- Switch off scroll bars by manipulating
document.body.style.overflow
during a resize. - Store and compare window dimensions before invoking your logic to ensure it only reacts to actual changes.
Storing the resize timeout reference id
Keep the global scope clean and tidy! Use jQuery.data()
to stash away our timeout references:
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:
Was this article helpful?