Lesson 19 of 50 – Timers
38% Completed
38%

Node.js Timers

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.

In simple words: Timers help us run code later or repeatedly. Common timer functions are setTimeout(), setInterval(), clearTimeout(), and clearInterval().

1. What Are Timers in Node.js?

Node.js provides timer functions that schedule callbacks. They are useful for delayed messages, repeated tasks, reminders, and other time-based operations.

Common Timer Functions
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.

2. Using setTimeout()

The setTimeout() function schedules a callback to execute after a specified delay in milliseconds.

Example: Display a Message After 3 Seconds
console.log('Start');

setTimeout(function () {
    console.log('Hello Students!');
}, 3000);

console.log('End');
Output:
Start
End
Hello Students!

The delay 3000 means 3000 milliseconds, or 3 seconds.

The delay is a minimum scheduling delay, not a guarantee of the exact execution time. The callback may run later if the event loop is busy.

3. Using an Arrow Function with setTimeout()

We can also use an arrow function as the callback.

Example: Arrow Function
setTimeout(() => {
    console.log('Welcome to Node.js!');
}, 2000);
Output After Approximately 2 Seconds:
Welcome to Node.js!

This example uses an arrow function instead of a regular function.

4. Passing Arguments to setTimeout()

Additional arguments supplied after the delay are passed to the callback function.

Example: Passing a Student Name
function greet(name) {
    console.log('Hello ' + name);
}

setTimeout(greet, 2000, 'Rahul');
Output After Approximately 2 Seconds:
Hello Rahul

Here, 'Rahul' is passed to the greet() function when the timer callback runs.

5. Using clearTimeout()

The clearTimeout() function cancels a timeout before its callback executes.

Example: Cancel a Timeout
const timer = setTimeout(() => {
    console.log('This message will not appear.');
}, 3000);

clearTimeout(timer);

console.log('Timer cancelled.');
Output:
Timer cancelled.

The callback is cancelled before it executes, so the message inside the timeout is not printed.

6. Using setInterval()

The setInterval() function schedules a callback to repeat after each interval while the interval remains active.

Example: Display a Message Every Second
setInterval(() => {
    console.log('Hello Students!');
}, 1000);
Example Output:
Hello Students!
Hello Students!
Hello Students!
...
This interval keeps repeating until it is cleared or the Node.js process exits. Use clearInterval() when the repeated task should stop.

7. Stop an Interval with clearInterval()

We can use clearInterval() to stop a repeating timer. In this example, the counter stops after five messages.

Example: Count from 1 to 5
let count = 0;

const timer = setInterval(() => {
    count++;

    console.log(count);

    if (count === 5) {
        clearInterval(timer);
        console.log('Timer stopped.');
    }
}, 1000);
Output:
1
2
3
4
5
Timer stopped.

The counter increases every second. When it reaches 5, clearInterval() stops the timer.

8. Using setImmediate()

The setImmediate() function schedules a callback to execute in the check phase of the Node.js event loop.

Example: setImmediate()
console.log('First');

setImmediate(() => {
    console.log('Immediate callback');
});

console.log('Second');
Output:
First
Second
Immediate callback

The synchronous statements execute before the scheduled immediate callback in this example.

9. Understanding Timer Execution Order

Timer callbacks do not interrupt currently running JavaScript. Synchronous code runs first, and scheduled callbacks run when the event loop reaches the appropriate phase.

Example: Synchronous Code and a Timer
console.log('A');

setTimeout(() => {
    console.log('B');
}, 0);

console.log('C');
Output:
A
C
B

Even with a delay of 0, the timeout callback does not run immediately. The synchronous code executes first.

10. Practical Example: Countdown Timer

This program displays a countdown from 5 to 1 and then prints a completion message.

Complete Program
let seconds = 5;

const countdown = setInterval(() => {
    console.log(seconds);

    seconds--;

    if (seconds === 0) {
        clearInterval(countdown);
        console.log('Countdown finished!');
    }
}, 1000);
Output:
5
4
3
2
1
Countdown finished!

Save the code as countdown.js and run it using node countdown.js.

11. Important Timer Concepts

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.

📝 Practical Assignment

Practice Tasks
Create programs for the following tasks:
  1. Display "Welcome Students" after 5 seconds using setTimeout().
  2. Display numbers from 1 to 10 using setInterval().
  3. Stop the interval when the counter reaches 10.
  4. Create a timeout and cancel it using clearTimeout().
  5. Display "Good Morning" three times at one-second intervals.
  6. Create a countdown from 10 to 1.

Challenge: Create a timer that displays "Time is over!" after 10 seconds and stops all active timers used by the program.


🧠 Quiz – Node.js Timers

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?