Javascript/jquery: $(window).resize how to fire AFTER the resize is completed?
To trigger a function after resizing completes, try debouncing in JavaScript. Here's a fundamental implementation:
This listener fires the console.log
function after a 250ms delay following the end of the resize event.
Performance optimization
Resize callbacks can fire dozens of times per second during window resizing which can strain system resources, especially on complexes apps or older devices. Here are various optimization techniques to maintain your app's performance:
Introducing throttle
Throttling is debouncing's less aggressive cousin. It allows for a maximum number of function calls over a given time:
Unique ids to avoid collisions
When using multiple instances of resize callbacks, ensure each callback has a unique id to keep them from tripping over each other:
Lib-erating your code with Lodash or Underscore.js
If your motto is "Why do it myself when a library can do it for me?", then Lodash or Underscore.js can help with their pre-built debounce functions:
Remember, including heavy libraries just for a single debounce function may be overkill, but if you're already using these libraries elsewhere, go ahead!
It's a bird, it's a plane, it's... resizeEnd
?
In complex scenarios, a custom event might be appropriate for different parts of your application to detect when resizing ends:
Using global variables or data attributes for timers
Storing the timer in a global variable or data attribute can be useful to access it from different functions or scopes:
By associating the timer with the window itself, you ensure a more efficient management of the delay and reduce potential conflicts.
Was this article helpful?