Debounce and throttle simplified
technikhil314
Posted on February 18, 2022
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);
💖 💪 🙅 🚩
technikhil314
Posted on February 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How I Created Vanilla Calendar Pro — A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024