Created
April 6, 2022 08:31
-
-
Save oreillyross/3aed3edc8a3b6b5207166ae1c9ac66f2 to your computer and use it in GitHub Desktop.
Timeout function to use for promise based functions, to guarantee a timeout to a network request for example
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, promise) { | |
let timeOutId; | |
const timeOutPromise = new Promise((_, reject)) => { | |
timeOutId = setTimeout(() => { | |
reject(new Error(`The operation timed out at ${ms} s`)); | |
}, ms) | |
} | |
return Promise.race([promise, timeOutPromise]).finally(() => { | |
clearTimeOut(timeOutId) | |
}); | |
} | |
timeout(3000, fetch...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment