Skip to content

Instantly share code, notes, and snippets.

@insin
Last active June 22, 2018 16:55
Show Gist options
  • Save insin/388285219a976c99c2b0 to your computer and use it in GitHub Desktop.
Save insin/388285219a976c99c2b0 to your computer and use it in GitHub Desktop.
Cancellable callback wrapper
/**
* 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