DEV Community

loading...

Discussion on: Ever heard of debouncing in in javascript , What is it ?

Collapse
lexlohr profile image
Alex Lohr

It's a bit more straight forward in modern JavaScript:

const debounce = (fn, delay) => {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), delay)
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
lukeshiru profile image
LUKESHIRU

Indeed, and you can also make it a curried function, and even add types with JSDocs!

/** @param {number} delay */
const debounce = delay => {
    /** @type {number} */
    let timer;

    /**
     * @template {Function} Callback
     * @param {Callback} callback
     * @returns {(...parameters: Parameters<Callback>) => void}
     */
    const debounced =
        callback =>
        (...parameters) => {
            clearTimeout(timer);
            timer = setTimeout(() => callback(...parameters), delay);
        };

    return debounced;
};

const debounce100 = debounce(100);
const debounce100Log = debounce100(console.log);

debounce100Log("hello");
debounce100Log("world");
Enter fullscreen mode Exit fullscreen mode
Collapse
ashishjshetty profile image
Ashish J shetty Author

Thank you !!
, this is also a great suggestion.

Collapse
ashishjshetty profile image
Ashish J shetty Author

thank you , this looks simpler.