The overview ended on a question from the laundry room at 14 Ferris Road: How do you wait for the washer without standing over it? Every program you’ve written so far ran top to bottom, with nothing to wait for. Real programs wait all the time. They wait for a timer, for a file to load from disk, or for a server on the other side of the world to reply.
In this lesson, you’ll see why the waiting you already know how to write freezes a program, and you’ll write your first reminder that waits without freezing anything. You’ll also learn to predict the order in which such a program prints its lines. Start with the most direct way to wait, which is to keep checking the clock.
Block While You Wait
Ines has started washer 1, and she wants a message when the cycle ends. With the JavaScript you know, the only way to wait is a loop that keeps checking the time until enough of it has passed. Date.now() returns the current time in milliseconds, so a loop can compare it with an end time.
To see what that loop does to a program, try it in the Node.js REPL. You need a current version of Node.js installed and a terminal. The examples use Node.js 26.
Type node in your terminal and press Enter to start the REPL, then define waitFor() and call it with three seconds, or 3,000 milliseconds:
> function waitFor(ms) {
… const end = Date.now() + ms;
… while (Date.now() < end) {
… // Keep checking the clock
… }
… }
undefined
> waitFor(3000)
undefined
As soon as you press Enter after waitFor(3000), type "Is the dryer free?" and press Enter again. Nothing answers. The REPL only prints the string three seconds later, once waitFor() has returned. For those three seconds, Node.js couldn’t run any other JavaScript, not even the REPL reading your input.
This happens because JavaScript runs your code on one thread: one sequence of steps, carried out one at a time. The while loop keeps that thread busy, so your next command has to wait its turn. Code that holds the thread like this is blocking. Code that runs this way, each line finishing before the next one starts, is synchronous.
A three-second wait is a toy example, of course. A real washer takes about an hour, and a program might wait a second or more for a server to reply. A program that blocks for that long can’t answer Kofi or remind anyone else while it waits. That’s why this course only uses a busy loop as a demo.
Schedule Work for Later
What Ines needs is a way to say “run this when the cycle’s done” and then carry on. That’s what setTimeout() does. You give it a function and a delay in milliseconds, and it arranges for the function to be called once the delay has passed.
The setTimeout() function isn’t part of the JavaScript language itself. Node.js provides it, and browsers provide a similar setTimeout() of their own.
You’ve passed functions around as values before, for example to .map(). A function you hand to another function for it to call is a callback. The callback you give .map() runs straight away, while .map() is running. The callback you give setTimeout() runs later, once the delay has passed.
This time, you’ll write a script rather than type into the REPL, so leave the REPL first: type .exit and press Enter, or press Ctrl+D. You’re back at your terminal’s prompt. Create a folder for this course and move into it:
$ mkdir laundry
$ cd laundry
In that folder, create a file called washer.mjs using your editor:
washer.mjs
console.log("Ines starts washer 1");
setTimeout(() => {
console.log("Washer 1 done: Ines, collect your laundry");
}, 3000);
console.log("Kofi asks: is the dryer free?");
The arrow function is the callback, and 3000 is the delay. Save washer.mjs, then run it from the laundry folder in your terminal:
$ node washer.mjs
Ines starts washer 1
Kofi asks: is the dryer free?
Washer 1 done: Ines, collect your laundry
Watch the timing as well as the order. The first two lines appear together, straight away. The reminder appears three seconds later, and then the program ends. Node.js keeps the program running while a timer is still waiting, then exits once nothing is left to do.
Note: The laundry room runs on a fast clock. A cycle ends in seconds, a reminder repeats every second, and housemates turn up moments later, where a real house would take minutes or hours. Short delays let you run each example without waiting around. Only the numbers change with the timescale, not the code.
If you know a sleep function from another language, note that setTimeout() isn’t one. It schedules the callback and returns at once, and only the callback waits.
Watch out for one slip here. Pass setTimeout() the function itself, without calling it. With a remind() function, setTimeout(remind(), 3000) calls remind() right away and hands setTimeout() its return value instead of a function. Node.js throws TypeError [ERR_INVALID_ARG_TYPE]: The "callback" argument must be of type function. Write setTimeout(remind, 3000) instead.
To predict the order of a script like this, sort its lines into two groups. Now is everything that runs while the script goes from top to bottom, including the setTimeout() call itself. Later is a callback scheduled to run afterward, like the one you pass to setTimeout(). It runs after the now part has finished and its delay has passed. In washer.mjs, both “Ines starts” and “Kofi asks” print now, and the reminder prints later.
Node.js does the waiting. It keeps track of the timer outside your code, which leaves the thread free for everything else. This is asynchronous code: you start something that takes time, hand over a callback, and carry on.
Timers are one example. Programs also wait for a file to load from disk or for a server to reply, and they usually use asynchronous functions for those jobs too, so the program doesn’t sit still while it waits. The function you call decides whether the program blocks. Node.js also has functions that read a file synchronously, blocking the thread until the file has loaded. You can read more about asynchronous programming in the RealJS glossary.
Sorting lines into now and later takes a little practice. The button below opens a chat with your AI mentor, with a question already typed in and a pointer to this section. Send it, and the mentor gives you small scripts one at a time, so you can sort their lines and get feedback on each answer:
Send a Reminder With Zero Delay
Sometimes there’s nothing left to wait for. When the program checks the laundry room, washer 2 has already finished Wren’s load, while washer 1 and the dryer are still running. The reminder for Wren should go out right away, so a delay of 0 seems right:
check_machines.mjs
console.log("Checking the laundry room");
setTimeout(() => {
console.log("Washer 2 done: Wren, collect your laundry");
}, 0);
console.log("Washer 1 is still running");
console.log("The dryer is still running");
Before you run it, write down the order in which you expect the four lines to print. Then run node check_machines.mjs in your terminal and compare the output with your prediction.
JavaScript prints the four lines in this order:
$ node check_machines.mjs
Checking the laundry room
Washer 1 is still running
The dryer is still running
Washer 2 done: Wren, collect your laundry
Wren’s reminder prints last, even though its delay is zero. If you expected it second, at the spot where setTimeout() appears in the script, you made the most common guess.
A setTimeout() callback can only run once the code that’s running now has finished, however short its delay. The setTimeout() call still only schedules the callback. Node.js can’t call it until the whole script has run from top to bottom. A delay of zero means “as soon as you’re free,” not “now”.
You can confirm this yourself. Add ten more console.log() lines after the last one, and run the file again. Wren’s reminder is still the last line.
Then try something more drastic. Paste the waitFor() function from the REPL into the file and call waitFor(2000) as the script’s last line. Now the zero-delay reminder arrives two seconds late, because the busy loop occupies the thread and the callback has to wait until it’s free.
So far, one rule covers it. A callback scheduled with setTimeout() runs later, after the current code has finished. Behind the scenes, Node.js decides when “later” can start. You’ll see how it decides, with a picture of what’s going on, further on in this course. That’s all you need about it for now.
If the zero-delay result still feels odd, talk it through with your mentor. This button opens the same chat with the question below ready to send. Try answering it in your own words first, then send it and compare your reasoning with the mentor’s:
Check Your Understanding
Try these three questions before you open the answers. The first one is about a script from the laundry room and the output it prints:
dryer.mjs
console.log("Dev loads the dryer");
setTimeout(() => {
console.log("Dryer done: Dev, collect your laundry");
}, 2000);
console.log("Dev goes upstairs");
console.log("Dev starts some homework");
When Dev runs it, the terminal shows this, with the last line arriving about two seconds after the others:
$ node dryer.mjs
Dev loads the dryer
Dev goes upstairs
Dev starts some homework
Dryer done: Dev, collect your laundry
- Kofi reads the output and says
setTimeout()paused the script for two seconds, like a sleep function. Label eachconsole.log()call indryer.mjsnow or later, and use your labels to explain to Kofi what really happened. - Why does
waitFor(3000)freeze the REPL, while asetTimeout()with a 3,000-millisecond delay doesn’t? - Node.js offers two functions that read the house rota from a file. The first returns only once the file’s contents are ready. The second returns at once and calls a callback with the contents once they’re ready. Both read the same file. Which one is asynchronous, and which one lets the program keep sending reminders while the disk does its work?
- “Dev loads the dryer”, “Dev goes upstairs” and “Dev starts some homework” are now, so they print together, straight away. The callback’s “Dryer done” line is later, so it prints about two seconds after the others. If
setTimeout()had paused the script, “Dev goes upstairs” would have waited two seconds too. Instead,setTimeout()only scheduled the callback and returned at once, and only the callback waited. - The
whileloop inwaitFor()runs on the only thread your code has, so nothing else can run until it ends.setTimeout()schedules its callback and returns at once, and Node.js keeps track of the time outside your code, so the thread stays free. - The second function is asynchronous, and it’s the one that lets the program carry on. It hands over a callback and returns, so the thread stays free while the disk works, as it does with
setTimeout(). The first function is synchronous: it blocks the thread until the file has loaded, much likewaitFor(), so no reminder can go out in the meantime. The job is the same in both cases, so the difference comes from the function you call.
You’ve now written a reminder that waits without freezing anything, and you can read a program’s output as now and later. Next, in Schedule and Cancel a Reminder, you’ll tell the reminder which housemate to notify, and you’ll learn how to call it off when it’s no longer needed.