How to create a debounce function in JavaScript

Here is one approach you might take to implement a debounce function.

The first argument is the function you’d like to debounce. The second argument represents the amount of time between function calls. If the third argument is a truthy value, the leading edge will be used. The following debounce function uses the trailing edge by default.

debounceTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function debounce(fn, wait, immediate = false) {
let timeout;
return function(...args) {
clearTimeout(timeout);
const callNow = immediate && !timeout;
timeout = setTimeout(() => {
timeout = null;
if (!immediate) fn(...args)
}, wait);
if (callNow) fn(...args);
}
}