Created
May 8, 2015 20:31
-
-
Save tkellen/df0421ca8a888029f243 to your computer and use it in GitHub Desktop.
wrap a method so it can be cancelled
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
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