Skip to content

Instantly share code, notes, and snippets.

@iOliverNguyen
Last active January 26, 2021 08:09
Show Gist options
  • Save iOliverNguyen/9617218a57f568f98d5e4e059aeb734f to your computer and use it in GitHub Desktop.
Save iOliverNguyen/9617218a57f568f98d5e4e059aeb734f to your computer and use it in GitHub Desktop.
// execute function(s) with a limit timeout, throws error if the function(s)
// do not complete within the given time
export function execWithTimeout(timeout, ...promises) {
let timeoutId;
const countDown = new Promise((_, reject) => {
timeoutId = setTimeout(reject, timeout, new Error('timed out'));
});
return Promise.race([countDown, ...promises]).then((result) => {
clearTimeout(timeoutId);
return result;
});
}
// example usage
async function doSomething() {
const resp = await fetch('https://registry.npmjs.org/react')
const body = await resp.json()
console.log(body.name)
}
execWithTimeout(1000, doSomething())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment