How to Debounce a Resize Event in jQuery
Debouncing a window resize event in jQuery ensures that your callback function executes only once after the user has finished resizing their browser, rather than firing continuously during the action. This article explains why the standard jQuery resize event causes performance issues and provides step-by-step code implementations using custom JavaScript debounce functions as well as utility libraries to optimize your application's responsiveness.
The Problem with the Default Resize Event
The standard browser resize event can fire dozens of
times per second while a user drags the browser window border. Attaching
resource-intensive tasks—such as DOM recalculations, layout adjustments,
or API calls—directly to this event causes layout thrashing and
noticeable interface lag:
// Inefficient: runs dozens of times per second during resize
$(window).on('resize', function() {
console.log('Window resized:', $(window).width());
});Implementing a Custom Debounce Function
The most lightweight way to debounce the handler without external
dependencies is to write a generic debounce helper function. A debounce
function uses JavaScript closures and setTimeout to delay
execution until a specific idle period has passed.
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context, args);
}, wait);
};
}Attaching the Debounced Handler in jQuery
Pass your event callback through the debounce function
when binding it to the $(window).on('resize') listener.
Specify the delay in milliseconds (typically between 150ms and 300ms
depending on user experience requirements):
function handleWindowResize() {
const windowWidth = $(window).width();
const windowHeight = $(window).height();
console.log(`Resized to: ${windowWidth}x${windowHeight}`);
// Place layout adjustment or element calculations here
}
// Bind the debounced function with a 250ms delay
$(window).on('resize', debounce(handleWindowResize, 250));Using Lodash or Underscore
If your project already includes Lodash or Underscore, you do not
need to write a custom debounce function. You can use the built-in
_.debounce method directly with jQuery:
// Using Lodash's _.debounce method
$(window).on('resize', _.debounce(function() {
console.log('Finished resizing:', $(window).width());
}, 200));Removing the Debounced Event Listener
If you dynamically remove event listeners in single-page applications to prevent memory leaks, store the debounced function reference before binding:
const debouncedResize = debounce(handleWindowResize, 250);
// Attach
$(window).on('resize', debouncedResize);
// Detach when destroying the view or component
$(window).off('resize', debouncedResize);