JS Debounce Explained

  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)
    }
}