Sleep and timeout in JavaScript
A promise that resolves after a delay, plus the timeout that races against it.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function withTimeout(promise, ms) {
const timeout = sleep(ms).then(() => {
throw new Error(`timed out after ${ms}ms`);
});
return Promise.race([promise, timeout]);
}
Keywords and builtins used here
Promiseasyncconstfunctionreturnthrow
The run, in numbers
- Lines
- 8
- Characters to type
- 245
- Tokens
- 74
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 42 seconds.
Step 3 of 3 in Scheduling, step 14 of 19 in Promises & async.