Learn why some steps are waits and how a program can wait without standing still: synchronous code runs line by line, asynchronous code starts a wait and goes on. Use setTimeout to run a callback later, see why three timers take 3 seconds rather than 6, and why a value a callback sets must be used inside it.
Fundamentals
TypeScript
What asynchronous code is and why it exists. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
On Saturday morning you load the washing machine, press Start, and
walk away. The wash takes an hour, and it does not need you for any of
it: you make tea, hang up a shirt, answer a message. When the machine
beeps, you go back and take the laundry out. Nobody stands in front of
a washing machine for an hour, watching the drum turn.
Every program you have written so far would stand there. In this
lesson you start a wait, let the program go on while the wait runs,
and say what happens when it ends. By the end you can write a program
that waits without standing still, and say in which order it prints
its lines.
Every line waits for the one before
Lesson 1.1 showed how a program runs: top to bottom, one line at a
time, each line finished before the next one starts. Code that runs
this way is synchronous: each line waits for the one before it to
finish, and the lines run in the order you wrote them.
For the work you have done so far, that costs nothing. Adding up
minutes, sorting tasks, checking a title: the computer does each of
these itself, faster than you could notice.
Some steps are different: they are waits. A reminder that should
appear in two minutes. A file the program has to read, or tomorrow's
weather from a website, which takes a moment to answer; Module 12
teaches both. During a wait the computer has
nothing to work on. It is waiting for time to pass, or for something
outside the program to answer. A synchronous program would stand still
for the whole wait, and nothing else in it could happen.
Start it now, finish it later
The way out is the one you use with the washing machine: start the
wait, say what should happen when it ends, and go on with something
else. Code that works this way is asynchronous, the opposite of
synchronous: some of its work starts now and finishes later, and the
lines after it do not wait for it.
Node's simplest asynchronous tool is setTimeout, a timer. You give
it two things: a callback, the function to run when the time is up
(lesson 5.4), and how long to wait, in milliseconds (ms), thousandths
of a second: 2000 is two seconds (2 s). setTimeout starts the
timer, hands it the callback, and returns at once, so the next line
runs straight away.
Here is a program of five lines: line 1 prints that a reminder is set,
lines 2 to 4 set a two-second timer for the reminder, and line 5
prints Back to the list. The figure runs it both ways. Standing
still means the program waits until the timer is done, and only then
goes on to line 5; With setTimeout, it goes on at once. Press
Next step to walk through it, or let it play, and switch between
the two ways:
Node never stands still for a timer; the first way is only there to
compare.
Now run the real one. Here is remind.ts; press Run to start it:
The callback is an arrow function with no parameters, () => { … }:
the timer passes it no values. The first two lines appear at once. The
third comes two seconds later, and only then does the run end: just as
the figure showed, line 5 does not wait for the timer, and Node does
not end the program while a timer still counts. The page's Run ends
when Node's run would, so it waits for the timer too.
Your own programs run in your terminal, so do it there as well. In
~/projects/taskkit, save the same code as remind.ts. Check the file
with npm (Node package manager, the tool that runs the project's
scripts), then run it with Node:
The check prints only its two > lines, so it passes: TypeScript
already knows setTimeout, from its own built-in definitions and from
@types/node, which you installed in lesson 2.8. Node prints:
In the terminal, too, the prompt comes back only after that third line.
Many waits at once
Waiting without standing still is most useful when a program waits for
more than one thing. Make three.ts in the same folder. It sets three
reminders, of 3, 1 and 2 seconds, then prints one line:
Run it:
Here is the run, second by second:
CallMom
Buymilk
Payrent
Terminal
Call Mom: counts 3 scounts3scounts3s
Buy milk: counts 1 s
The three timers count at the same time, and each callback runs when its
own time is up. So the reminders come out in the order their times end,
whatever order you wrote them in. That is why asynchronous code exists: a
program that waits for a timer, a file and a website waits for all three
at once, and is free for other work in the meantime.
Predict the order
Node counts a timer of 0 as one millisecond, almost nothing to wait
for. Read this program, then decide which line it prints first.
Predict
Which line does this program print first?
The common mistake: using a value too early
The callback runs later, but the line under setTimeout runs now. So a
box that the callback fills is still empty on that line.
Common mistake
Using what a callback sets, before it has run
Make later.ts in the taskkit folder. The callback fills note, and
the line after the timer prints it:
Run npm run check. It prints its two > lines, and then:
The error has a code, TS2454 (TS for TypeScript, then the number of
the error). Line 5 runs a second before line 3 fills the box.
Variable 'note' is used before being assigned.
The fix
Move the line that needs the value into the callback, after the line
that fills it:
TypeScript does not know when a callback will run, or whether it will,
so it never counts a box filled inside a callback as filled on the
lines outside it. Here it is right: run node later.ts anyway, and Node
prints Reminder: undefined. So when a value comes from a callback, use
it inside that callback. Making the time shorter does not help, not even
0: the line below still runs first.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. Try it before you open the hints;
they come one at a time.
Recap
Recap · 3 questions
Check yourself
What makes code asynchronous?
Check yourself
What does setTimeout(callback, 2000) do?
Check yourself
A callback fills note. Where can you print it?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
What asynchronous code is and why it exists
What things are
Word
What it means
Synchronous
Each line waits until the one before is done
Asynchronous
Starts now, finishes later; the next lines go on
A wait
A timer, a file or a website, not work to do
Millisecond
A thousandth of a second: 2000 is 2 s
Code
Write
To
setTimeout(callback, 2000)
Run callback once, 2 seconds from now
setTimeout(() => {…}, 0)
Run the callback after the running lines
Rules
Rule
What it means
The next lines go first
Lines after setTimeout run before its callback
Waits overlap
Timers count at once; the shortest ends first
Node waits for timers
The program ends when no timer is left
Use it inside
A value a callback sets is used in that callback
Where to go next
You can now tell a wait from work, start a wait with setTimeout
without stopping the program, and say in which order such a program
prints: the lines running now first, then each callback when its time
is up.
Next is The event loop, in pictures, which opens up what this
lesson only described: where a callback waits for its turn, and why
even a zero-millisecond timer lets the rest of the file finish first.
Before you move on, change the three times in three.ts, predict the
order and the length of the run, then check with node three.ts. When
you are done, delete remind.ts, three.ts, zero.ts and later.ts
from the taskkit folder: they are not part of TaskKit, and a
later.ts that still holds the mistake keeps npm run check red.
Terminal: Back to the listBacktothelistBacktothelist
Time
Line 1 prints at once.
If the program stood still, nothing else could run for two
whole seconds.
The reminder prints after the two seconds.
Line 5 comes last, two seconds late.
Standing still holds line 5 back; with setTimeout it runs at once
All 4 steps shown.Step 1 of 4: Terminal: Reminder set: call MomStep 2 of 4: Your code: stands still, 2 sStep 3 of 4: Terminal: Reminder: call MomStep 4 of 4: Terminal: Back to the list
Line 2 hands the callback to a timer and goes straight on.
The timer counts on its own. None of your lines is running.
Line 5 prints at once, two seconds before the reminder.
The file is done, but Node does not end: a timer still counts.
Two seconds are up. The timer hands the callback back to run.
The reminder prints. Nothing is left to wait for, so Node ends.
Standing still holds line 5 back; with setTimeout it runs at once
All 7 steps shown.Step 1 of 7: Terminal: Reminder set: call MomStep 2 of 7: Your code: setTimeoutStep 3 of 7: Timer: counts 2 sStep 4 of 7: Terminal: Back to the listStep 5 of 7: Your code: nothing to runStep 6 of 7: Your code: the callbackStep 7 of 7: Terminal: Reminder: call Mom
All 7 steps shown.
counts1scounts1s
Pay rent: counts 2 scounts2scounts2s
Terminal: Reminders setReminderssetRemindersset
Terminal: Buy milkBuymilkBuymilk
Terminal: Pay rentPayrentPayrent
Terminal: Call MomCallMomCallMom
Time
Three timers count at once: the run takes 3 s, not 6
Exercise · Read the code
Set a reminder
Which line prints Call Mom three seconds from now, and lets the lines
after it run at once?
Exercise · Read the code
How long does it run?
You run this program with node. How long does it take, from pressing
Enter (Return on a Mac) until the prompt comes back?
The four console.log lines below should print what Node prints when
it runs plants.ts, in the same order. They are in the order the file
is written. Put them in Node's order.