Loading video player…

Repeat Work With setInterval()

In this lesson, Dev’s laundry is done, but one reminder isn’t enough to bring Dev down from upstairs. You turned the reminder into a nag that repeats every second until Dev collects the laundry.

Key Points

  • Like setTimeout(), setInterval() takes a callback and a delay in milliseconds. A timeout calls its callback once. An interval calls it again and again, every time the delay passes.
  • An interval never stops on its own. As long as one is active, Node keeps your program running, and you press Ctrl+C to end it.
  • setInterval() returns a handle. Pass that handle to clearInterval() to stop the interval. Once it’s cleared, no more calls come.
  • Node counts each delay of an interval from when the last call started, not from when it ended. A slow callback uses part of that delay: with a 600-millisecond check on a 1000-millisecond interval, only 0.4 seconds of rest is left between calls. That rest is the time your program is free for other work.
  • A chained timeout, a function that schedules itself again with setTimeout() at the end of its own run, waits at least the full delay after each call ends, however long the call took.
  • Each new timer has a new handle, and the function stores each one in the same variable, so that variable is declared with let, not const. The function only runs later, after the script has finished, so by then the variable exists.
  • An interval counts from each start, and a chained timeout counts from each end. Neither is exact: as Kofi’s late reminder showed in Schedule and Cancel a Reminder, a timer that’s due waits while JavaScript is busy. Later in this course, you’ll see why.

The Final Code

The nag, with a timeout that plays the part of Dev coming down for the laundry after three and a half seconds:

Language: JavaScript Filename: nag.mjs
const start = Date.now();
const seconds = () => ((Date.now() - start) / 1000).toFixed(1);

const nag = setInterval(() => {
  console.log(`${seconds()}s Dev, your laundry is done`);
}, 1000);

setTimeout(() => {
  clearInterval(nag);
  console.log(`${seconds()}s Dev collected the laundry`);
}, 3500);

Run it with Node, and it prints:

Language: Shell
$ node nag.mjs
1.0s Dev, your laundry is done
2.0s Dev, your laundry is done
3.0s Dev, your laundry is done
3.5s Dev collected the laundry

Three nags print, at one, two and three seconds. The interval is cleared at three and a half seconds, so the nag due at four seconds never comes.

The chained version, where a busy loop stands in for a slow check of every machine:

Language: JavaScript Filename: chained_nag.mjs
const start = Date.now();
const seconds = () => ((Date.now() - start) / 1000).toFixed(1);

const checkMachines = () => {
  const end = Date.now() + 600;
  while (Date.now() < end) {}
};

const remind = () => {
  console.log(`${seconds()}s nag starts`);
  checkMachines();
  console.log(`${seconds()}s nag ends`);
  nag = setTimeout(remind, 1000);
};

let nag = setTimeout(remind, 1000);

setTimeout(() => clearTimeout(nag), 4500);

Each nag ends, and only then does a full second of rest begin:

Language: Shell
$ node chained_nag.mjs
1.0s nag starts
1.6s nag ends
2.6s nag starts
3.2s nag ends
4.2s nag starts
4.8s nag ends

Next, in Debounce a Chatty Sensor, the dryer gets a door sensor that reports every jiggle, and a timer that waits until the door goes quiet.

00:00 Dev’s laundry is done, and the washer has stopped. You already know how to send Dev a reminder with a timeout. The helper at the top stamps each line with the seconds since the program started.

00:13 You run it with Node. One second later, the reminder prints. Then the program ends.

00:21 However, Dev is upstairs with headphones on. One reminder can slip past. So Dev needs a nag, a reminder that repeats every second until Dev collects the laundry.

00:34 For that, Node gives you setInterval(), a second timer function. Like setTimeout(), it takes a callback and a delay in milliseconds.

00:43 The difference is what happens after the callback runs. A timeout calls it once. An interval calls it again, every thousand milliseconds.

00:54 Run the program, and the nag prints at one second, then at two, then at three. It never stops on its own. As long as an interval is active, Node keeps your program running, so you press Ctrl+C to end it.

01:11 To stop an interval, you need its handle. Like a timeout, setInterval() returns one. The constant nag keeps it. Then a timeout plays the part of Dev.

01:23 After three and a half seconds, Dev comes down for the laundry. The callback passes the handle to clearInterval(), and logs that Dev collected it.

01:33 So, how many nags does Dev get? Your turn: pause the video and predict the count.

01:44 Three. The nags arrive at one, two and three seconds. At three and a half seconds, the interval is cleared, so the nag due at four seconds never comes. That’s the rule for an interval: it repeats on its own until you clear it with its handle.

02:03 Now, say each nag first checks every machine, and that check is slow. Here, a busy loop stands in for it. It holds JavaScript for six hundred milliseconds, like the frozen program from the start of this section.

02:17 It’s a toy, but real work can take that long. The nag now logs when it starts and when it ends. Run it. The first nag starts at one second and ends at one point six.

02:32 The next one starts at two seconds.

02:35 Node counts each second from when the last nag started, not from when it ended. The check uses six tenths of that second. So the rest between nags shrinks to four tenths of a second.

02:47 That rest is the time your program is free for other work, like answering Kofi.

02:54 With a slow check every second, your program is free less than half the time. If it needs more time for other work, you can repeat with a timeout that sets the next timeout.

03:06 The remind function nags, does its slow check, and only then schedules itself again, a second later. Each new timer has a new handle, and remind stores each one in nag.

03:19 So this time, nag is declared with let, not const, because it gets a new value each time. The function only runs later, after the script has finished, so by then nag already exists.

03:32 Run it. The nags start at one second, then two point six, then four point two. Each one ends, and only then does a full second of rest begin.

03:45 So, an interval aims to start each nag a second after the last one started. Slow work eats into the rest. A chained timeout waits at least a full second after each nag ends.

03:58 One caveat, for later in this course: neither one is exact, because a timer that’s due waits while JavaScript is busy.

04:07 You’ve built a nag that repeats with an interval and stops when you clear its handle.

04:12 Next, in Debounce a Chatty Sensor, the dryer gets a door sensor that reports every jiggle, and a timer that waits until the door goes quiet.

Become a Member to join the conversation.