Timers in Node.js allow us to execute a function after a delay, repeat a function at intervals, or schedule a function to run after the current operation finishes.
setTimeout(), setInterval(),
clearTimeout(), and clearInterval().
Node.js provides timer functions that schedule callbacks. They are useful for delayed messages, repeated tasks, reminders, and other time-based operations.
| Function | Purpose |
|---|---|
setTimeout() |
Schedules a callback to run after a delay. |
clearTimeout() |
Cancels a timeout that has not executed. |
setInterval() |
Schedules a callback to repeat at intervals. |
clearInterval() |
Stops a repeating interval. |
setImmediate() |
Schedules a callback for the check phase of the event loop. |
The setTimeout() function schedules a callback
to execute after a specified delay in milliseconds.
console.log('Start');
setTimeout(function () {
console.log('Hello Students!');
}, 3000);
console.log('End');
Start
End
Hello Students!
The delay 3000 means 3000 milliseconds,
or 3 seconds.
We can also use an arrow function as the callback.
setTimeout(() => {
console.log('Welcome to Node.js!');
}, 2000);
Welcome to Node.js!
This example uses an arrow function instead of a regular function.
Additional arguments supplied after the delay are passed to the callback function.
function greet(name) {
console.log('Hello ' + name);
}
setTimeout(greet, 2000, 'Rahul');
Hello Rahul
Here, 'Rahul' is passed to the
greet() function when the timer callback runs.
The clearTimeout() function cancels a timeout
before its callback executes.
const timer = setTimeout(() => {
console.log('This message will not appear.');
}, 3000);
clearTimeout(timer);
console.log('Timer cancelled.');
Timer cancelled.
The callback is cancelled before it executes, so the message inside the timeout is not printed.
The setInterval() function schedules a callback
to repeat after each interval while the interval remains active.
setInterval(() => {
console.log('Hello Students!');
}, 1000);
Hello Students!
Hello Students!
Hello Students!
...
clearInterval()
when the repeated task should stop.
We can use clearInterval() to stop a repeating
timer. In this example, the counter stops after five messages.
let count = 0;
const timer = setInterval(() => {
count++;
console.log(count);
if (count === 5) {
clearInterval(timer);
console.log('Timer stopped.');
}
}, 1000);
1
2
3
4
5
Timer stopped.
The counter increases every second. When it reaches
5, clearInterval() stops the timer.
The setImmediate() function schedules a callback
to execute in the check phase of the Node.js event loop.
console.log('First');
setImmediate(() => {
console.log('Immediate callback');
});
console.log('Second');
First
Second
Immediate callback
The synchronous statements execute before the scheduled immediate callback in this example.
Timer callbacks do not interrupt currently running JavaScript. Synchronous code runs first, and scheduled callbacks run when the event loop reaches the appropriate phase.
console.log('A');
setTimeout(() => {
console.log('B');
}, 0);
console.log('C');
A
C
B
Even with a delay of 0, the timeout callback
does not run immediately. The synchronous code executes
first.
This program displays a countdown from 5 to 1 and then prints a completion message.
let seconds = 5;
const countdown = setInterval(() => {
console.log(seconds);
seconds--;
if (seconds === 0) {
clearInterval(countdown);
console.log('Countdown finished!');
}
}, 1000);
5
4
3
2
1
Countdown finished!
Save the code as countdown.js and run it
using node countdown.js.
| Concept | Explanation |
|---|---|
| Milliseconds | 1000 milliseconds equal 1 second. |
| Timeout | Schedules a callback to run after a delay. |
| Interval | Schedules a callback to repeat. |
| Cancellation | Uses clearTimeout() or clearInterval(). |
| Event loop | Coordinates when scheduled callbacks can execute. |
| setImmediate() | Schedules a callback for the check phase. |
setTimeout().setInterval().clearTimeout().Challenge: Create a timer that displays "Time is over!" after 10 seconds and stops all active timers used by the program.
Select the correct answer for each question.
1. Which function schedules a callback after a delay?
2. Which function stops a repeating interval?
3. How many milliseconds are there in one second?