Skip to content

Instantly share code, notes, and snippets.

@jonathanrodriguezs
Created June 15, 2020 06:14
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 jonathanrodriguezs/f9d157730669bb03c0d58dca7f015e15 to your computer and use it in GitHub Desktop.
Save jonathanrodriguezs/f9d157730669bb03c0d58dca7f015e15 to your computer and use it in GitHub Desktop.
Set a timeout in ms to resolve a promise
function timeout(ms, promise) {
let timeoutID;
const timeoutPromise = new Promise((_, reject) => {
timeoutID = setTimeout(() => {
reject(Error(`Operation timed out after ${ms}ms`))
}, ms)
})
return Promise
.race([promise, timeoutPromise])
.finally(() => {
clearTimeout(timeoutID)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment