Skip to content

Instantly share code, notes, and snippets.

@rkatic
Last active January 19, 2021 07:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkatic/5d376d524292d1792bc27a3436e1cd37 to your computer and use it in GitHub Desktop.
Save rkatic/5d376d524292d1792bc27a3436e1cd37 to your computer and use it in GitHub Desktop.
Simple promise based timeout implementation.
function timeout (ms, x) {
return new Promise((resolve, reject) => {
let timeoutId = setTimeout(() => {
timeoutId = null
reject('timeout')
}, ms)
const onSettle = () => {
if (timeoutId != null) {
clearTimeout(timeoutId)
resolve(x) // propagate fulfilment/rejection
}
}
Promise.resolve(x).then(onSettle, onSettle)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment