Last active
June 22, 2018 16:55
-
-
Save insin/388285219a976c99c2b0 to your computer and use it in GitHub Desktop.
Cancellable callback wrapper
This file contains 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 function with a .cancel() function which can be used to prevent the | |
* given function from being called. | |
* | |
* Use case: triggering an asyncronous function with new data while an existing | |
* function for the same task but with old data is still pending a callback, so | |
* the callback only gets called for the last one to run. | |
*/ | |
function cancellable(func) { | |
var cancelled = false | |
var cancellabled = function() { | |
if (!cancelled) { | |
func.apply(null, arguments) | |
} | |
} | |
cancellabled.cancel = function() { | |
cancelled = true | |
if (typeof func.onCancel == 'function') { | |
func.onCancel() | |
} | |
} | |
return cancellabled | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment