Created
May 15, 2016 06:13
-
-
Save not-an-aardvark/28e06e1fdda30335c4c9850ae26cd6de 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
/* 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