Introduction to throttling
Throttling is another browser optimization method. It is derived from the word to throttle .To throttle an engine is basically a mechanism in which we control the rate of fluid flow is managed by obstruction or constriction.
On similar lines in throttle or control the rate of API calls being made.
Deeper Understanding of throttling
In throttle, we basically check for the time difference after the first call,if the time difference between the first and the next calls is equal to delay then we let the settimeout call the callback function
Throttling Code
function throttle(callback, delay) {
// Write your code here.
//there are two cases that we need to handle
//case 1 when the first time the call is made then first execute the callback and start the delay
// we also need to store the time of the first call and which will be used to find the time difference between subsequent calls.If the time difference becomes equal to the delay only then make a calle1r
// case 2 when we are in 2nd or more calls now we need to check did the timer
//elapse and since the last call made and then only make a call
//difference between throttle and debouncing is in debouncing
//on the first call we make the call to the callback and start the timer
// on the second call we will clear the timer until on every call
// and again start the timer from 0
// the timer will elapse in some time but since on every call after the first call we will
// keep on resetting the timer
// suppose if no call is made after the first call now the timer has the opportunity to complete its timeout and make the call to the callback
// so indirectly after the first call for the second,third,ith call the timer will run only when its delay will get expired
var timerId;
var lastcall=0;
const throttlefunction=function(...args){
const currenttime=Date.now();
const timesincelastcall=currenttime-lastcall;
const delayremaining=delay-timesincelastcall;
if(delayremaining<=0){
/// this is when the timer has not expired
// do nothing
lastcall=currenttime;
callback.apply(this,args);
}
else{
//first time call
clearTimeout(timerId);
timerId=setTimeout(()=>{
//update lastcall
lastcall=Date.now();// we want the time of the callback function and not the time when the throttle function is called
callback.apply(this,args);
},delayremaining);
}
}
throttlefunction.cancel=function(){
clearTimeout(timerId);
}
return throttlefunction
}
Which Scenario to use throttling
click1(start timer) click2(time difference < delay no call) click3(time difference < delay no call) click4(time difference > delay make call)