Schedule and Cancel a Reminder

In the last lesson, Ines got her first reminder: three seconds after she started washer 1, a callback printed “Washer 1 done: Ines, collect your laundry”. That reminder works, but it only ever reminds Ines, and once it’s scheduled, nothing can stop it. A real laundry room needs more than that.

In this lesson, you’ll tell a reminder which housemate and which machine it’s for, and you’ll call a reminder off when it’s no longer needed. You’ll also find out what a timer’s delay really promises, which is less than it seems.

Tell the Reminder Who to Remind

A reminder that names its housemate needs a function that takes the name as a parameter. Here’s remind(), which also takes the machine:

Language: JavaScript
function remind(name, machine) {
  console.log(`${machine} done: ${name}, collect your laundry`);
}

You can’t write setTimeout(remind("Kofi", "Washer 1"), 2000). As you saw in the last lesson, the parentheses call remind() right away, and setTimeout() receives undefined instead of a function, so Node.js throws a TypeError.

You could wrap the call in an arrow function, () => remind("Kofi", "Washer 1"), and that works. However, setTimeout() passes any arguments you give it after the delay to the callback when it runs. Save this as reminders.mjs:

Language: JavaScript Filename: reminders.mjs
function remind(name, machine) {
  console.log(`${machine} done: ${name}, collect your laundry`);
}

setTimeout(remind, 2000, "Kofi", "Washer 1");
setTimeout(remind, 3000, "Dev", "Dryer");
console.log("Two reminders scheduled");

The first call says: in 2,000 milliseconds, call remind("Kofi", "Washer 1"). Run the file:

Language: Shell
$ node reminders.mjs
Two reminders scheduled
Washer 1 done: Kofi, collect your laundry
Dryer done: Dev, collect your laundry

The first line prints now, Kofi’s reminder two seconds later, and Dev’s a second after that. One remind() function serves the whole house.

The arrow function and the extra arguments behave differently when a variable changes between scheduling the timer and running its callback. In this script, nextUp holds the name of whoever is using washer 1. Kofi starts it, two reminders are scheduled, and then the program moves nextUp along to Wren, who’s waiting her turn:

Language: JavaScript Filename: next_up.mjs
let nextUp = "Kofi";

setTimeout(() => {
  console.log(`Arrow function: ${nextUp}, collect your laundry`);
}, 1000);

setTimeout((name) => {
  console.log(`Extra argument: ${name}, collect your laundry`);
}, 1000, nextUp);

nextUp = "Wren";

Run it, and the two reminders disagree about whose laundry it is:

Language: Shell
$ node next_up.mjs
Arrow function: Wren, collect your laundry
Extra argument: Kofi, collect your laundry

The arrow function is a closure: it reaches the variable nextUp itself, not a copy of its value, and it reads nextUp when it runs. That happens later, after nextUp = "Wren" has run now. The extra argument is different. Its value is read now, at the moment you call setTimeout(), and kept until the callback runs. So when a reminder must use the value a variable has when you schedule it, pass that value as an extra argument.

That holds for strings and numbers. An object passed this way is still the same object, so if its properties change before the callback runs, the callback sees the changes. Pass the property itself, such as housemate.name, when you need its value from scheduling time.

Explaining this difference in your own words is a good way to find out whether it has sunk in. The button below opens a chat with your AI mentor. It includes the question already typed in and a pointer to this section. Write your explanation of why the two reminders in next_up.mjs named different housemates, then send it. The mentor tells you what you got right and what’s missing:

Call Off a Reminder

Kofi loads washer 1 and starts it, then spots a red sock among his white shirts. He stops the washer at once. His reminder is still scheduled, though, and in two seconds it’ll tell him to collect laundry that never got washed.

To cancel a timer, you need a way to point at it. Every call to setTimeout() returns a handle, a value that identifies that one timer. Pass the handle to clearTimeout(), and the timer is canceled: its callback never runs. Save the handle in a variable when you schedule Kofi’s reminder, and call clearTimeout() when Kofi stops his washer:

Language: JavaScript Filename: red_sock.mjs
function remind(name, machine) {
  console.log(`${machine} done: ${name}, collect your laundry`);
}

const kofiReminder = setTimeout(remind, 2000, "Kofi", "Washer 1");
setTimeout(remind, 3000, "Dev", "Dryer");

setTimeout(() => {
  clearTimeout(kofiReminder);
  console.log("Kofi stopped washer 1: reminder called off");
}, 500);

Kofi stops the washer after half a second, which the third setTimeout() stands in for. Run the file:

Language: Shell
$ node red_sock.mjs
Kofi stopped washer 1: reminder called off
Dryer done: Dev, collect your laundry

Kofi’s reminder never prints, and Dev’s still arrives on time.

You don’t need to look inside a handle. In Node.js, it’s a Timeout object, and in a browser, it’s a number. Either way, you keep it and hand it back to clearTimeout(). Calling clearTimeout() with the handle for a timer that has already run does nothing, so it’s safe to try to call off a reminder even if it’s too late to cancel it.

Sort the Lost Socks

So far, every reminder has arrived when its delay said it would. Can you rely on that? Dev wants the house program to take on a bigger job too: sorting the lost-sock log, where every odd sock found in the machines gets a tag number. To keep that job from holding up anything else, he schedules it with a delay of 0, so it runs as soon as the program is free. Kofi’s reminder is due 100 milliseconds after the start.

The real log is a few dozen socks long, so this script fills the list with a million random tag numbers from Math.random(), which gives the sort enough work to take a while. On my machine, it takes about a second, much longer than the reminder’s 100 milliseconds. Save the script as lost_socks.mjs:

Language: JavaScript Filename: lost_socks.mjs
setTimeout(() => {
  console.log("Dev starts sorting the lost socks");
  const socks = [];
  for (let i = 0; i < 1000000; i++) {
    socks.push(Math.random());
  }
  socks.sort((a, b) => a - b);
  console.log("Lost socks sorted");
}, 0);

setTimeout(() => {
  console.log("Kofi, collect your laundry");
}, 100);

Before you run it, write down the order in which you expect the three lines to print. In particular, where does Kofi’s reminder go, given that it’s due long before the sort is done? Then run node lost_socks.mjs and compare.

Node.js prints the three lines in this order, on every computer:

Language: Shell
$ node lost_socks.mjs
Dev starts sorting the lost socks
Lost socks sorted
Kofi, collect your laundry

Kofi’s reminder comes last, and the last two lines appear together, about a second after the first. If you expected the reminder between the sort’s two lines, at the moment its 100 milliseconds were up, you made the most common guess.

The sort’s callback started first because its delay was 0. While it ran, the 100 milliseconds passed and Kofi’s reminder was due. However, a callback never interrupts another one. Once a callback starts, it runs to completion, and only then can the next one start. So Kofi’s reminder waited until the sort had finished. On my machine, it arrived about 900 milliseconds late.

Dev’s delay of 0 only postponed the sort. It didn’t stop the sort from holding up Kofi’s reminder: once its callback started, nothing else could run until it ended.

Nothing in this script waits on purpose. The sort shows how ordinary work in another callback is enough to hold up a timer. That’s how late timers happen in real programs.

So read a timer’s delay as “not before”, never as “exactly at”. A reminder with a delay of 100 milliseconds runs no sooner than 100 milliseconds from now, and later if other code is still running. A delay is a minimum, not a promise.

That’s also why a timer makes a poor clock: if you need to know how much time has really passed, measure it with Date.now(), which you met in the last lesson, instead of trusting the delay.

To see how late Kofi’s reminder is on your machine, add const start = Date.now(); as the script’s first line, and log Date.now() - start in the reminder’s callback. The number changes a little from run to run.

Later in this course, a picture of the event loop shows exactly why one callback has to wait for another, and how to split a long job so reminders arrive on time. That’s all you need to know about it for now.

If it still seems odd that a due reminder can’t cut in, put the reason into words and test it on your mentor. This button opens the same chat with the question below ready to send. Answer it yourself first and send your answer with it. The mentor then gives you feedback on your reasoning:

Check Your Understanding

Try these three questions before you open the answers. The first one is about a script for the dryer queue and the output it prints:

Language: JavaScript Filename: dryer_queue.mjs
let waiting = "Ines";

const nudge = setTimeout(() => {
  console.log(`Nudge: ${waiting}, the dryer is free`);
}, 500);

setTimeout((name) => {
  console.log(`Reminder: ${name}, the dryer is free`);
}, 1000, waiting);

waiting = "Dev";
clearTimeout(nudge);
console.log("Queue updated");

When Dev runs it, the terminal shows this, with the second line arriving about a second after the first:

Language: Shell
$ node dryer_queue.mjs
Queue updated
Reminder: Ines, the dryer is free
  1. The script sets waiting to "Dev" before any timer runs, yet the reminder names Ines, and the nudge never prints at all. Explain both.
  2. Using remind(), write the code that reminds Wren about washer 2 in four seconds, and the line that calls that reminder off.
  3. Ines says a reminder with a delay of 2,000 milliseconds always prints exactly two seconds later. When is she wrong, and how could her program find out how much time really passed?
  1. The reminder gets the name as an extra argument, and setTimeout() read that value now, when it was called, while waiting was still "Ines". Changing waiting afterward doesn’t touch the value already handed over. The nudge never prints because clearTimeout(nudge) cancels it now, long before its 500 milliseconds are up. If it had run, it would have said Dev, because its arrow function reads waiting later, when it runs.

  2. Keep the handle that setTimeout() returns, then pass it to clearTimeout(): const wrenReminder = setTimeout(remind, 4000, "Wren", "Washer 2"); schedules the reminder, and clearTimeout(wrenReminder); calls it off.

  3. A delay means “not before”. If other code is still running when the two seconds are up, such as another callback sorting a long list, the reminder waits until that code has finished, so it prints late. To find out how much time really passed, her program can save Date.now() when it schedules the reminder and subtract it from Date.now() when the reminder runs.

You can now schedule a reminder for any housemate and call it off with its handle. You also know that its delay is a minimum. Next, in Repeat Work With setInterval(), you’ll see a reminder that doesn’t stop after one message: it repeats until someone calls it off.

Become a Member to join the conversation.