Last active
January 19, 2018 10:41
-
-
Save GianlucaGuarini/78df965fa13064fb7caaa07931f12949 to your computer and use it in GitHub Desktop.
Functional advanced async (cancellable/abortable) `setTimeout` helper
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
/** | |
* Advanced async (cancellable/abortable) `setTimeout` helper | |
*/ | |
function wait(delay) { | |
return (val) => { | |
let timer | |
let abort | |
const p = new Promise(function(resolve, reject) { | |
abort = reject | |
timer = setTimeout(() => resolve(val), delay) | |
}) | |
p.cancel = () => clearTimeout(timer) | |
p.abort = reason => p.cancel() || abort(reason) | |
return p | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple example:
demo