Skip to main content
Back to blog list

Debounce and throttle simplified

· One min read

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

Debounce

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

How to use it

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

const throttleInput = throttle(showValue, 500);

const debouncedInput = debounce(showValue, 500);