DevAcademy
IntermediateNode.js

Timers

Schedule code to run later with setTimeout, setInterval, and setImmediate.

Reading Time

10 min

Lesson

Lesson 14 of 34

The Three Timer Functions

Node.js provides the same setTimeout and setInterval functions available in browsers, plus a Node-specific setImmediate. All three schedule a callback to run asynchronously, later.

setTimeout and clearTimeout

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

setInterval and clearInterval

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Timer Functions Compared

FunctionBehavior
setTimeout(fn, ms)Runs fn once, after at least ms milliseconds
setInterval(fn, ms)Runs fn repeatedly, roughly every ms milliseconds
setImmediate(fn)Runs fn on the next event loop iteration, after I/O callbacks

The Delay is a Minimum, Not a Guarantee

setTimeout(fn, 0) does not run fn immediately — it schedules fn for the next timers phase, which only happens once the currently executing synchronous code (and any pending microtasks) finish. Under heavy load, the actual delay can be noticeably longer than requested.

A Non-Blocking Delay Helper

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Best Practice

Always keep a reference to a timer if you might need to cancel it — an interval left running with no way to clear it is a classic source of memory leaks in long-running Node.js processes.

Interview Questions

Quick Quiz

1. What does setTimeout(fn, 0) actually guarantee?

2. What is a common cause of memory leaks involving timers?

3. How can setTimeout be used to build an awaitable delay?