Skip to content

Instantly share code, notes, and snippets.

@yyyyaaa
Forked from insin/cancellable.js
Created June 22, 2018 16:55
Show Gist options
  • Save yyyyaaa/d4570c51d36f54c404ee69854fb7f4c4 to your computer and use it in GitHub Desktop.
Save yyyyaaa/d4570c51d36f54c404ee69854fb7f4c4 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