Skip to content

Instantly share code, notes, and snippets.

@Tribhuwan-Joshi
Created May 20, 2023 15:23
Show Gist options
  • Save Tribhuwan-Joshi/734976231a1639e2cc8b7cda71e3c400 to your computer and use it in GitHub Desktop.
Save Tribhuwan-Joshi/734976231a1639e2cc8b7cda71e3c400 to your computer and use it in GitHub Desktop.
Given a function fn and a time in milliseconds t, return a throttled version of that function.
/*
A throttled function is first called without delay and then, for a time interval of t milliseconds, can't be executed but should store the latest function arguments provided to call fn with them after the end of the delay.
*/
const throttle = function (fn , t){
let intervalInProgress = null;
let argsToProcess = null;
const intervalFunction = () =>{
if(argsToProcess == null){
clearInterval(intervalInProgress);
intervalInProgress = null;
}
else {
fn(...argsToProcess);
argsToProcess = null;
}}
return function(...args) {
if(intervalInProgress){
argsToProcess = args;
}
else{
fn(...args);
intervalInProgress = setInterval(intervalFunction , t);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment