Skip to content

Instantly share code, notes, and snippets.

@not-an-aardvark
Created May 15, 2016 06:13
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 not-an-aardvark/28e06e1fdda30335c4c9850ae26cd6de to your computer and use it in GitHub Desktop.
Save not-an-aardvark/28e06e1fdda30335c4c9850ae26cd6de to your computer and use it in GitHub Desktop.
/* Returns a wrapped version of `func` which calls `func` at most once every `delay` milliseconds.
** The wrapped function returns a Promise which resolves with the result of calling `func` after the delay has finished.
*/
module.exports = (func, delay) => {
var lastTimestamp = -Infinity;
return function (...args) {
var now = Date.now();
lastTimestamp = Math.max(now, lastTimestamp + delay);
return new Promise(resolve => setTimeout(resolve, lastTimestamp - now)).then(() => func.apply(this, args));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment