Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Created April 6, 2022 08:31
Show Gist options
  • Save oreillyross/3aed3edc8a3b6b5207166ae1c9ac66f2 to your computer and use it in GitHub Desktop.
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
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