Created
May 20, 2023 15:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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