Simple debounce in vanilla JavaScript

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