Last active
January 19, 2021 07:33
-
-
Save rkatic/5d376d524292d1792bc27a3436e1cd37 to your computer and use it in GitHub Desktop.
Simple promise based timeout implementation.
This file contains hidden or 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
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