Skip to content

Instantly share code, notes, and snippets.

@seejohnrun
Last active December 17, 2015 23:09
Show Gist options
  • Save seejohnrun/5686982 to your computer and use it in GitHub Desktop.
Save seejohnrun/5686982 to your computer and use it in GitHub Desktop.
Tick tick tick...
// Grab a timebomb copy of a function that will expire in a certain time
// period - raising errors when called outside of that window
var timebomb = function (toCall, expireIn) {
// Expire the function call in expireIn ms
setTimeout(function () {
toCall = undefined;
}, expireIn);
// Return a wrapper function that will clear the timeout, and
// return the function execution if proper to do so
return function () {
if (toCall === undefined) {
throw new Error('Function call expired!');
}
return toCall.bind(this)();
};
};
// Create an array and a timebomb for the reverse method
var arr = [1, 2, 3, 4, 5];
var reverseMethod = timebomb(arr.reverse, 200).bind(arr);
// Keep using it until we can't
setInterval(function () {
console.log(reverseMethod());
}, 50);
/*
*
* [ 5, 4, 3, 2, 1 ]
* [ 1, 2, 3, 4, 5 ]
* [ 5, 4, 3, 2, 1 ]
* Error: Function call expired!
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment