Skip to content

Instantly share code, notes, and snippets.

@sanishkr
Created February 11, 2020 12:00
Show Gist options
  • Save sanishkr/95d7c0965a2b73a1de72f703af9a5247 to your computer and use it in GitHub Desktop.
Save sanishkr/95d7c0965a2b73a1de72f703af9a5247 to your computer and use it in GitHub Desktop.
const throttle = (fn, delay) => {
let lastRan;
let timerId;
return function() {
const ctx = this;
const args = arguments;
if(!lastRan){
fn.apply(ctx, args)
lastRan = Date.now();
} else {
console.log("trying...")
clearTimeout(timerId);
timerId = setTimeout(() => {
if(Date.now() - lastRan >= delay) {
fn.apply(ctx, args)
lastRan = Date.now();
}
}, lastRan - Date.now() + delay);
}
}
}
const logger = throttle(()=>console.log("Hello at "+ new Date), 2000)
setInterval(logger, 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment