DEV Community

technikhil314
technikhil314

Posted on

Debounce and throttle simplified

I was trying to create my own implementation of debounce and throttle. Yes just for fun.
and I came up with very simplified implementation that anyone can follow just by taking a look at the code.

You can play with the demo here

Hope you like it.

Throttle

function throttle(fun, timeduration) {
    let shouldCall = true;
    return (...args) => {
        if (shouldCall) {
            shouldCall = false;
            fun(...args);
            setTimeout(() => {
                shouldCall = true;
            }, timeduration)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Debounce

function debounce(fun, timeduration) {
    let lastTimeoutId = 0
    return (...args) => {
        if (lastTimeoutId) {
            clearTimeout(lastTimeoutId);
        }
        lastTimeoutId = setTimeout(() => {
            fun(...args);
        }, timeduration)
    }
}
Enter fullscreen mode Exit fullscreen mode

How to use it

function showValue(val) {
    console.log(val)
}

const throttleInput = throttle(showValue, 500);

const debouncedInput = debounce(showValue, 500);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)