Code That Runs Later

So far, every program you wrote ran in order. Each line finished before the next one started. This section is about code that runs later. It starts with one function, setTimeout:

console.log("first");
setTimeout(() => console.log("timeout"), 100);
console.log("last");

Output:

first
last
timeout

setTimeout takes two values: a function, and a delay in milliseconds (100 ms is a tenth of a second). It does not run the function now. It schedules it, which means it saves it to run later. Then it returns at once, and the program goes on.

So last prints before timeout, even though it is written after it. This is the main idea of the section: the order you write code in is not always the order it runs in.

The function you give to setTimeout is a callback, which you met in the Functions section: a function you pass to other code, so that it can call it later.

Why does JavaScript work this way? It often runs in places that must keep reacting. A web page that stopped for two seconds to wait for something would freeze. A server that waited for one user's slow request would ignore all the other users. So JavaScript does not wait. Slow work is scheduled with a callback, and the rest of the code keeps running.

Even a delay of 0 does not run the callback right away. It waits until all the normal code has finished:

setTimeout(() => console.log("timeout"), 0);
console.log("normal code");

Output:

normal code
timeout

The part of JavaScript that runs these waiting callbacks is called the event loop. You will see how it works in a later lesson of this section.

setInterval is similar, but it runs the callback again and again, until you stop it with clearInterval:

let count = 0;
const timer = setInterval(() => {
  count++;
  console.log("tick", count);
  if (count === 3) {
    clearInterval(timer);
  }
}, 100);

Output:

tick 1
tick 2
tick 3

In the exercise, use setTimeout so a line that is written in the middle of the program prints last.