Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created December 7, 2012 13:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieMason/4233170 to your computer and use it in GitHub Desktop.
Save JamieMason/4233170 to your computer and use it in GitHub Desktop.
until(fn:Function, delay:Number):Function
/**
* Returns a function which won't be invoked until delay has elapsed, without further calls being made during that interval.
* If further calls are made, the delay is reset and the cycle repeats.
* @param {Function} fn Behaviour to be wrapped in this delay
* @param {Number} delay Duration in milliseconds
* @return {Function}
*/
function until(fn, delay) {
var timeoutId;
var scheduledCall = setTimeout.bind(window, fn, delay);
return function() {
clearTimeout(timeoutId);
timeoutId = scheduledCall.apply(this, arguments);
};
}
@JamieMason
Copy link
Author

Example

var snarfLater = until(function () {
  console.log('snarf!');
}, 2000);

snarfLater();
snarfLater();
snarfLater();
snarfLater();

... 2 seconds pass

>> "snarf!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment