Simple debounce in vanilla JavaScript

Posted . Visible to the public.

Debouncing a method call delays its execution until after a specified time has passed.
If it's called again before that time has passed, its execution is delayed again.

This technique is commonly used to improve performance when code would be run more often than it needs to.
One example for that are scroll event handlers in JavaScript: You want to react to a user scrolling, but it's enough to do that when they have stopped scrolling.

Here is a small JavaScript function that you can use for that:

function debounce(callback, delay) {
  let timer
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      callback.apply(this, args)
    }, delay)
  }
}

Usage example

function onScroll() {
  ...
}
window.addEventListener('scroll', debounce(onScroll, 300))

(If your project uses LoDash, you can use lodash-es/debounce instead. It's a bit heavier, but can do more.)

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2024-08-06 10:34)