Published on

Custom debounce function in JavaScript

Authors

Naive Implementation

debounce.js
const debounce = (func, delay) => {
    let id;
    return (...args)=>{
        if(id) {
            clearTimeout(id);
        }
        id = setTimeout(()=>{
            func(...args);
        }, delay)
    }
}

What

In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event.

Why

Debouncing is used primarily for rate-limiting.

How

In our implementation, the debounce function returns a debounced function. Which when called, will run only after the user specified delay in miliseconds.

The way this works is, the first time when user calls our debounced function -

  1. We initialise our setTimeout call with the provided delay which immediately returns us an id.

Every setTimeout returns an id which is of number type. It's primarily used to clear any currently ongoing setTimeout by simply passing the id to clearTimeout function.

  1. This id remains valid only until our delay is elapsed. After which the id becomes undefined.

  2. Thus, on every single debounced function call we simply check if there is an id.

  3. If there is one, we clear our ongoing setTimeout call and re-initialise a new setTimeout call.

  4. Else, the setTimeout will run to completion and call our passed in function func after the specified delay.