Skip to content

Instantly share code, notes, and snippets.

@mvasin
Last active September 19, 2018 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvasin/771f4eff5d8fadae2f3ddcbb9222f77e to your computer and use it in GitHub Desktop.
Save mvasin/771f4eff5d8fadae2f3ddcbb9222f77e to your computer and use it in GitHub Desktop.
// 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