Created
February 11, 2020 12:00
-
-
Save sanishkr/95d7c0965a2b73a1de72f703af9a5247 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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