Using A Debounce Function In JavaScript
JavaScript
25/07/2022
A debounce function groups several function calls into one single call under the condition that they occur close enough to each other.
This is not to be confused with throttling, which limits function calls to a given time interval. Check out this visual example for the difference.
Debounce explained
Check this scenario out: Imagine your debounce function has a timeout of 300 milliseconds as specified below. If the same function is called 10 times with each call happening less than 300ms apart, the function will be executed on the 10th time, on the condition that the 11th function call does not occur or happens more than 300ms after the 10th one.
function debounce(func, timeout = 300) { let timer return (...args) => { clearTimeout(timer) timer = setTimeout(() => { func(...args) }, timeout) }}
Practical application
We can apply this scenario to the mousemove
event. Our callback function will be triggered on the condition that the mouse event is, at some point, called more than 500ms apart.
window.addEventListener( "mousemove", debounce(() => console.log("Debounced!"), 500))