What is Throttling? How to implement it in JS?
Dileep Reddy
Posted on November 14, 2022
Throttling is a method used to limit the number of times a function can be executed.
Throttling - No matter how many times a function is fired, it will be executed only once in a given time interval
Let's say we have an expensive function which does heavy computation or calls a costly 3rd party API.
const expensive = () => {
console.log('Expensive function');
}
We can limit the number of times the function can be executed by using throttling. Let's write a simple throttle function.
const throttle = (fn, delay) => {
let wait = false;
const throttledFunction = () => {
if (wait) return; // If wait is true, it means the timer
// is still running and the function shouldn't be executed
fn();
wait = true;
setTimeout(() => {
wait = false;
}, delay);
return throttledFunction;
}
const inExpensive = throttle(expensive, 1000);
Our throttle function takes a callback function and delay and returns its throttled counterpart(inExpensive).
But wait, our throttle function cannot handle arguments. Let's improve it a bit so that it can take arguments.
const throttle = (fn, delay) => {
let wait = false;
let storedArgs = null;
const throttledFunction = (...args) => {
if (wait) {
storedArgs = args;
return
}
fn(...storedArgs);
wait = true;
setTimeout(() => {
wait = false;
}, delay);
}
return throttledFunction;
}
Thanks for reading!....
https://medium.com/walkme-engineering/debounce-and-throttle-in-real-life-scenarios-1cc7e2e38c68
https://www.freecodecamp.org/news/javascript-debounce-example/
https://egghead.io/lessons/javascript-build-lodash-debounce-from-scratch
Posted on November 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 23, 2022