Debounce a Function in JavaScript to Avoid Multiple Calls When Resizing
The debounce function. This waits a set time period for an event to stop before running. Debounce is used whenever we only want to call a function once per a triggering event. When an event happens, we delay the execution of the function by the timeout
duration, in this case, 300ms. If the event happens again before the function has been executed, we delay for a further 300ms after clearing the previous timer. This article on CodeCamp has an example that inverts the logic and executes with the first event while ignoring subsequent ones within the time period, such as you might want to do with a double click.
const debounce = ( func, timeout = 300 ) => {
let timer;
return ( ...args ) => {
clearTimeout( timer );
timer = setTimeout( () => {
func.apply( this, args );
}, timeout );
};
}
Function to do something based on a window width. This could be anything. To test it out, replace the if/else
logic with a console log indicating that the function has been called and then resize the window a few times.
const myFunction = () => {
if ( window.innerWidth >= 992 ) {
doSomething();
} else {
doSomethingElse();
}
}
Wrap the call to debounce the function in another function so it can be called as an object:
const doSomethingOnResize = debounce(() => myFunction());
Add an event listener:
window.addEventListener( 'resize', doSomethingOnResize )
Feedback?
Email us at enquiries@kinsa.cc.