Codiqo

Learn JavaScript · lesson 41 of 60 · about 9 minutes

setTimeout() and Callbacks

Add a view counter to Sam's page: run code later with setTimeout, pass callbacks to functions, and see how the event loop orders things.

What you'll learn

  • Schedule code with setTimeout
  • Pass callbacks to functions
  • Predict the order of async output

A view counter

Sam's page is going online, and Sam wants it to count its views. The count lives on Sam's server, so asking for it takes a moment. countView(callback) sends the request and returns straight away; when the server answers, it calls your callback with the new total. Until then the page shows Counting views..., and the callback replaces it with 1,235 views, or You're the first visitor! when the total is 1.

Not everything happens straight away

Some work takes time: timers, network requests, reading files. JavaScript doesn't stop and wait. It carries on, and runs a callback function when the work is done.

setTimeout(callback, ms) runs the callback after at least that many milliseconds.

Order of events

console.log("1. Start");
setTimeout(() => console.log("3. Timer done"), 100);
console.log("2. Carry on");

Output

1. Start
2. Carry on
3. Timer done

Callbacks that bring back an answer

A function that has to wait for something can take a callback and call it with the answer once it has one. The code after the call doesn't wait: it runs first, and the callback runs later with the result. That's exactly how countView works.

Waiting for an answer

function lookUp(name, callback) {
  setTimeout(() => callback(name.length), 20);
}
console.log("Asking...");
lookUp("Sam", (letters) => console.log(`Sam has ${letters} letters`));
console.log("Still going");

Output

Asking...
Still going
Sam has 3 letters

The event loop

JavaScript runs one thing at a time. Timers and other finished work wait in a queue. Only when the current code has completely finished does the event loop take the next item from the queue.

That's why even setTimeout(fn, 0) runs after the code below it.

Zero isn't immediate

setTimeout(() => console.log("timeout 0"), 0);
for (let i = 1; i <= 2; i++) {
  console.log("loop", i);
}
setTimeout(() => console.log("timeout 50"), 50);
setTimeout(() => console.log("timeout 10"), 10);

Output

loop 1
loop 2
timeout 0
timeout 10
timeout 50

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.