Skip to content

Instantly share code, notes, and snippets.

@jamesfulford
Last active August 13, 2023 07:17
Show Gist options
  • Save jamesfulford/3449cca94fc87a51dd2cae5608868f73 to your computer and use it in GitHub Desktop.
Save jamesfulford/3449cca94fc87a51dd2cae5608868f73 to your computer and use it in GitHub Desktop.
// Promis-ifying `setTimeout`, handy to have
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Example promise-creator. This one happens to load scripts synchronously in a browser,
// but you can work with any kind of promise here, even in node.
function getScript(src) {
return new Promise((resolve, reject) => {
const element = document.createElement('script');
element.src = src;
// May not play well with old browsers, but that's not the point of this gist
element.onload = resolve;
element.onerror = reject;
// Adding to document causes network request
document.body.appendChild(element);
});
}
Promise.race([
// Start loading script
getScript('/async-script.js'),
// If script doesn't load in 10 seconds, throw the race (timeout)
timeout(10 * 1000).then(() => {
throw new Error("Script did not load within 10 seconds.")
}),
// NOTE: timeout does not cancel the underlying network request. (script loading cannot be cancelled, anyway)
])
// Handling for when script loads (maybe `await` this `Promise.race` expression)
.then(console.log)
// Handling for when script fails or times out
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment