I am currently learning debounce in Javascript and I came across two ways of writing debounce functions that works the same. One is a lot simpler like regular function, the other one is the complicated one that everyone seems to use.
Version 1:
@index.html
<input type="text" oninput="betterFunction()">
@script.js
function getData() {
console.log('Data Fetched')
}
function debounce(callback, delay) {
let timer
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
callback();
}, delay)
}
}
const betterFunction = debounce(getData, 1000)
Version 2:
@index.html
<input type="text" oninput="debounce()">
@script.js
let timer
function debounce() {
clearTimeout(timer)
timer = setTimeout(() => {
console.log('Data Fetched');
}, 1000)
}
What is the difference between these two ways of debouncing if they both gives the same result?
PS: I am surprised that I have never seen anyone use the ‘version 2’, ofcourse something must me wrong. Could anybody explain the differences please?
2
Answers
Version 1 is better, because it:
timer
(timeout ID) within the scope of—the lifetime of—the function callAn even-better debounce
Josh W Comeau has an informative article covering debounce.
Here is his (modified) minimal version:
Note: I replaced the
callback.apply(null, args)
with the more succinctcallback(...args)
Usage
Snippet
In the snippet below, points are drawn every time the user stops moving the mouse after 250ms. Each point is auto-removed after 2 seconds.
Debounce function is a javascript programming pattern for delaying execution of a function, your Version 1 is the commonly accepted pattern for implementing a debounce feature because its better than Version 2 for the reasons listed by MR. Polywhirl.
The pattern is actually making use of a javascript feature called a
closure
, which allows inner function (the function being returned by debounce) to access their outer scope (specifically in this case, the declared variabletimer
).You can read about closures in detail here to gain further understanding why version 1 is the preferred version, but this explanation/example of closures might be easier to grasp at first.