Timeout Promise

Add a timeout to any promise, rejecting with an error if the operation takes too long.

Code

Boilerplates
const withTimeout = (promise, ms) => Promise.race([
  promise,
  new Promise((_, reject) =>
    setTimeout(() => reject(new Error('Timeout')), ms)
  )
]);

const fast = new Promise(r => setTimeout(() => r('completed'), 10));
return await withTimeout(fast, 1000);
Browser·fetch() may be limited by CORS

More JavaScript Snippets