Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Last active January 19, 2018 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GianlucaGuarini/78df965fa13064fb7caaa07931f12949 to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/78df965fa13064fb7caaa07931f12949 to your computer and use it in GitHub Desktop.
Functional advanced async (cancellable/abortable) `setTimeout` helper
/**
* 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
}
}
@GianlucaGuarini
Copy link
Author

GianlucaGuarini commented Jan 19, 2018

Simple example:

const wait2sec = wait(2000)

const job1 = wait2sec('job1 done')
const job2 = wait2sec('job2 done')
const job3 = wait2sec('job3 done')

job1.then(console.log)
// cancellable 
job1.cancel()
job2.then(console.log)

// abortable!
job3.then(console.log).catch(console.log)
job3.abort('Aborted')

demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment