What may be confusing you is that you don't call debounce()
repeatedly. If you did, then yes, the timeout
variable would be unique to each invocation.
What you do instead is call debounce()
once. It returns a function which you then can call repeatedly. Because this function is nested inside debounce()
alongside the timeout
variable, each time you call it, it uses the same timeout
variable.
David Walsh's article has an example:
var myEfficientFn = debounce( function() {
// All the taxing stuff you do
}, 250 );
window.addEventListener( 'resize', myEfficientFn );
Note that we only call debounce()
once here, and it returns a function which is saved as myEfficientFn
. Then myEfficientFn
gets called on every resize
event, but the callback function passed into debounce()
is only called after there are no more resize
events for 250 milliseconds.
You could also write that code equivalently as:
window.addEventListener( 'resize', debounce( function() {
// All the taxing stuff you do
}, 250 ) );
Here it may look like you're calling debounce()
multiple times, but you aren't. It's only being called once, at the time you call addEventListener()
. The actual event listener function here isn't debounce()
, it's the function that debounce()
returned.
Or, for more clarity, let's break it apart step by step and use better names:
// Called after at least one resize event has fired but 250 milliseconds
// have gone by without another resize event.
function handleResizeAfterIdle() {
// All the taxing stuff you do
}
// Create a function with debouncing that can be used as a resize event
// listener. resizeListener will be called on *every* resize event,
// but handleResizeAfterIdle will be called only after 250 milliseconds
// have elapsed with no more resize events.
var resizeListener = debounce( handleResizeAfterIdle, 250 );
// Now we can add the event listener.
window.addEventListener( 'resize', resizeListener );