Throttle function can be used to execute a function more than once every X milliseconds. The main difference between Debounce function and Throttle function is that throttle function gurantees the execution of function every X milliseconds.
In this tutorial, we will create a Throttle function and check out the live demo to understand it’s working.
Consider the following HTML code.
And, the following JavaScript code.
console.log("You have clicked a button");
};
If you click on the button say 100 times in a minute, sayHello() function will be called 100 times.
By using the Throttle function, we can limit the number of function calls. For example, if we add the throttle of 2 seconds, then the function will be called every 2 seconds despite the number of clicks.
Here is our Throttle function. Our function accepts two arguments, the first argument is the function to execute and the second argument is the delay.
let lastCalled = 0;
return (...args) => {
let now = new Date().getTime();
if(now - lastCalled < delay) {
return;
}
lastCalled = now;
return fn(...args);
}
}
When the throttle function is called, we check if the time difference between the current call and the last call is greater than the delay assigned by the callee function.
If it’s greater than delay, we simply execute the assigned function, if it’s less than the delay, we do nothing.
Here is how we call the Throttle function.
console.log("You have clicked a button");
};
const sayHello = throttle(printMessage,2000);
Now, if you click the button say 100 times in a minute, the throttle will call the function after every 2 seconds. To check out the demo, refer to the pen below.
See the Pen
Throttle Function in JavaScript by Shahid Shaikh (@codeforgeek)
on CodePen.
I recommend you to open the pen and check the messages in the console.