How to wait before running code
Short answer
setTimeout() runs a function after the given number of milliseconds:
setTimeout(() => console.log('one second later'), 1000);
console.log('right now');Output:
right now
one second laterA sleep function
Wrap setTimeout() in a promise, and you can wait with await:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log('start');
await sleep(500);
console.log('half a second later');Output:
start
half a second laterPauses in a loop
With await inside a for...of loop each step waits for the previous one:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (const step of [3, 2, 1]) {
console.log(step);
await sleep(300);
}
console.log('Go!');Output:
3
2
1
Go!Cancelling
setTimeout() returns an id. clearTimeout() cancels the planned call:
const timer = setTimeout(() => console.log('never shown'), 1000);
clearTimeout(timer);
console.log('cancelled');Output:
cancelledCommon mistake
setTimeout() does not stop the program: the code after it runs immediately. And forEach() does not wait for await in its function, so all pauses start at once:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const start = Date.now();
[1, 2, 3].forEach(async (n) => {
await sleep(300);
console.log(n, Date.now() - start < 400 ? 'all at once' : 'one by one');
});Output:
1 all at once
2 all at once
3 all at onceFunctions used in this recipe
- setTimeout — Runs a function once after a delay.
- Promise — A promise of a result that will be ready later: success or failure.