Execute Program

JavaScript Concurrency: Sequential setTimeouts

Welcome to the Sequential setTimeouts lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We can schedule a timer inside the callback of another timer.

  • >
    const array = [];
    setTimeout(() => {
    setTimeout(() => {
    array.push('it worked');
    }, 500);
    }, 500);
    array;
    Asynchronous Icon Async Result:
    ['it worked']Pass Icon
  • As usual, we can see what's happening in detail by adding some console.log calls. In this example, pay special attention to when the second timer is scheduled.

  • >
    console.log('scheduling first timer');
    setTimeout(first, 1000);

    function first() {
    console.log('scheduling second timer');
    setTimeout(second, 1000);
    }

    function second() {
    console.log('it worked');
    }
    Asynchronous Icon async console output
  • The first timer is scheduled immediately after the program starts running. It finishes around a second later, and its callback schedules the second timer. The second timer resolves a second after that, at the two-second mark.

  • Here's a larger example with three timers arranged sequentially. Each timer schedules the next timer. We push into the array at each point to verify that they're running in the expected order.

  • >
    const array = [];
    setTimeout(() => {
    array.push(1);
    setTimeout(() => {
    array.push(2);
    setTimeout(() => {
    array.push(3);
    }, 500);
    }, 500);
    }, 500);
    array;
    Asynchronous Icon Async Result:
    [1, 2, 3]Pass Icon
  • Here's what happens during that code example, in detail:

    1. The first timer is scheduled for 500 ms.
    2. The initial code example finishes, returning array, which is currently empty.
    3. After 500 ms, the first timer finishes. It pushes 1 onto the array, then schedules the second timer.
    4. 500 ms later, the second timer finishes, pushes 2, and schedules the third timer.
    5. 500 ms after that, the third timer finishes and pushes 3.
    6. No more asynchronous code is waiting, so Execute Program shows the result. The whole process took about 1500 ms (500 + 500 + 500).
  • Note that the examples in this lesson never had more than one timer scheduled at a time! These timers were sequential: each timer schedules the next one only after its own delay has finished.

  • As usual, the JavaScript engine never runs two pieces of code at the same time. All that we're doing is scheduling function calls to happen in the future.