Skip to content

Instantly share code, notes, and snippets.

@tkellen
Created May 8, 2015 20:31
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 tkellen/df0421ca8a888029f243 to your computer and use it in GitHub Desktop.
Save tkellen/df0421ca8a888029f243 to your computer and use it in GitHub Desktop.
wrap a method so it can be cancelled
function cancellable(fn) {
var cancelled = false;
var wrapped = function() {
if (!cancelled) {
fn.apply(null, arguments)
}
};
wrapped.cancel = function() {
cancelled = true;
};
return wrapped;
}
var async = function (cb) {
setTimeout(function () {
cb(null);
}, 1000);
}
var callback = cancellable(function () {
console.log('yo, i called you back');
});
async(callback);
// callback.cancel();
// ^ call me before the timeout and i won't run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment