JS Debounce Explained

Ning KuangNing Kuang
1 min read
  1. store timeout about a callback, initial value is null

  2. return a function wrapping the original callback

  3. when timeout is null, clear the timeout

  4. then set a timer to execute callback with the set delay in ms, and store the timer id to variable timeout

function debounce(callback, delay) {
    let timeout = null

    return (...args) => {
        if (timeout !== null) clearTimeout(timeout)
        timeout = setTimeout(() => {
            callback.apply(this, args)
        }, delay)
    }
}
0
Subscribe to my newsletter

Read articles from Ning Kuang directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ning Kuang
Ning Kuang