Last active
September 19, 2018 16:46
-
-
Save mvasin/771f4eff5d8fadae2f3ddcbb9222f77e 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
// wait in milliseconds | |
function throttle(fn, wait) { | |
// unix timestamp | |
let lastTimeExecuted; | |
return function (args) { | |
const currentTime = new Date(); | |
// this condition is satisfied only the very first time | |
if (!lastTimeExecuted) { | |
lastTimeExecuted = currentTime; | |
fn(args); | |
return; | |
} | |
// we already have some date in lastTimeExecuted, so we calculate | |
// diff in milliseconds | |
const msPassed = currentTime.getTime() - lastTimeExecuted.getTime(); | |
// save it for feature runs | |
lastTimeExecuted = currentTime; | |
// runs original function only if `wait` time passed | |
if (msPassed > wait) fn(args) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment