Introduction
Node.js timers allow you to schedule code to run immediately after a delay, repeatedly at fixed intervals, or after the current operation finishes. They are commonly used for delayed tasks, repeated jobs, reminders, polling, and simple automation. In this chapter, you will practice setTimeout(), setInterval(), setImmediate(), clearTimeout(), clearInterval(), clearImmediate(), and practical timer examples step by step. Node.js Timers practice questions with solutions help to understand the concepts.
Question 1: How do you use setTimeout() in Node.js?
Problem
Display a message after 2 seconds using setTimeout().
Solution
setTimeout(() => {
console.log("Hello from Node.js!");
}, 2000);
Output
After approximately 2 seconds:
Hello from Node.js!
Step-by-Step Explanation
setTimeout() schedules a function to run after a specified delay.
The basic syntax is:
setTimeout(function, delay);
In this example:
2000
means 2000 milliseconds.
Since:
1000 milliseconds = 1 second
2000 milliseconds equals 2 seconds.
Question 2: How do you pass arguments to setTimeout()?
Problem
Create a function that accepts a student’s name and displays it after 2 seconds.
Solution
function showStudent(name) {
console.log("Student:", name);
}
setTimeout(showStudent, 2000, "Rahul");
Output
After approximately 2 seconds:
Student: Rahul
Step-by-Step Explanation
The function is:
function showStudent(name) {
console.log("Student:", name);
}
We pass the function to setTimeout():
setTimeout(showStudent, 2000, "Rahul");
The arguments after the delay are passed to the callback.
Here:
showStudent → callback
2000 → delay
"Rahul" → argument
Question 3: How do you use setInterval()?
Problem
Display a message every 1 second using setInterval().
Solution
let count = 1;
const timer = setInterval(() => {
console.log("Message", count);
count++;
}, 1000);
Output
Message 1
Message 2
Message 3
Message 4
...
The message continues every second.
Step-by-Step Explanation
setInterval() repeatedly executes a function at a specified interval.
Syntax:
setInterval(function, delay);
Here:
1000
means approximately one second between scheduled executions.
The count variable increases after every execution:
count++;
Question 4: How do you stop setInterval() using clearInterval()?
Problem
Display numbers every second, but stop the timer after 5 executions.
Solution
let count = 1;
const timer = setInterval(() => {
console.log("Count:", count);
if (count === 5) {
clearInterval(timer);
console.log("Timer stopped.");
}
count++;
}, 1000);
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Timer stopped.
Step-by-Step Explanation
First, we create an interval:
const timer = setInterval(() => {
// Code
}, 1000);
The returned timer ID is stored in:
timer
When the count reaches 5:
clearInterval(timer);
stops the repeated execution.
Question 5: How do you cancel setTimeout() using clearTimeout()?
Problem
Schedule a message after 5 seconds, but cancel it after 2 seconds.
Solution
const timer = setTimeout(() => {
console.log("This message will not appear.");
}, 5000);
setTimeout(() => {
clearTimeout(timer);
console.log("Timer cancelled.");
}, 2000);
Output
After approximately 2 seconds:
Timer cancelled.
The first message is not displayed.
Step-by-Step Explanation
First, we schedule the main timer:
const timer = setTimeout(() => {
console.log("This message will not appear.");
}, 5000);
The timer is supposed to execute after 5 seconds.
Then we create another timer:
setTimeout(() => {
clearTimeout(timer);
}, 2000);
After 2 seconds, clearTimeout() cancels the first timer.
Question 6: What is setImmediate() in Node.js?
Problem
Use setImmediate() to schedule a function to run after the current operation completes.
Solution
console.log("Start");
setImmediate(() => {
console.log("setImmediate executed.");
});
console.log("End");
Output
Typically:
Start
End
setImmediate executed.
Step-by-Step Explanation
The first statement runs:
console.log("Start");
Then setImmediate() schedules its callback.
The next statement runs:
console.log("End");
After the current synchronous work finishes, Node.js executes the setImmediate() callback.
Question 7: How do you cancel setImmediate()?
Problem
Schedule a callback with setImmediate() and cancel it before it executes.
Solution
const timer = setImmediate(() => {
console.log("This message will not appear.");
});
clearImmediate(timer);
console.log("Immediate timer cancelled.");
Output
Immediate timer cancelled.
Step-by-Step Explanation
First, we schedule the callback:
const timer = setImmediate(() => {
console.log("This message will not appear.");
});
The timer handle is stored in:
timer
We then cancel it:
clearImmediate(timer);
Therefore, the callback does not execute.
Question 8: How do you create a countdown timer?
Problem
Create a countdown from 5 to 1 and display "Time's up!" after the countdown finishes.
Solution
let count = 5;
const timer = setInterval(() => {
console.log(count);
count--;
if (count === 0) {
clearInterval(timer);
console.log("Time's up!");
}
}, 1000);
Output
5
4
3
2
1
Time's up!
Step-by-Step Explanation
We start with:
let count = 5;
Every second, the interval executes:
console.log(count);
Then the value decreases:
count--;
When the value reaches zero:
if (count === 0)
we stop the interval:
clearInterval(timer);
Finally:
console.log("Time's up!");
is displayed.
Question 9: How do you create a delayed task using async/await?
Problem
Create a reusable delay() function and use it with async/await.
Solution
function delay(milliseconds) {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
async function start() {
console.log("Task started.");
await delay(2000);
console.log("Task completed after 2 seconds.");
}
start();
Output
Immediately:
Task started.
After approximately 2 seconds:
Task completed after 2 seconds.
Step-by-Step Explanation
The delay() function returns a Promise:
function delay(milliseconds) {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
When the timer finishes, resolve() is called.
Inside the async function:
await delay(2000);
waits for the Promise to resolve.
Output
Task 1
Task 2
Task 3
with approximately one second between each message.
Question 10: How do you build a practical Node.js auto-save timer?
Problem
Create a simple auto-save simulation that runs every 3 seconds and automatically stops after 3 saves.
Solution
let saveCount = 1;
const autoSaveTimer = setInterval(() => {
console.log(
`Saving data... Save ${saveCount}`
);
console.log("Data saved successfully.");
saveCount++;
if (saveCount > 3) {
clearInterval(autoSaveTimer);
console.log("Auto-save stopped.");
}
}, 3000);
Output
After approximately 3 seconds:
Saving data... Save 1
Data saved successfully.
After approximately 6 seconds:
Saving data... Save 2
Data saved successfully.
After approximately 9 seconds:
Saving data... Save 3
Data saved successfully.
Auto-save stopped.
Step-by-Step Explanation
Step 1: Create a counter
let saveCount = 1;
This keeps track of the number of saves.
Step 2: Start the interval
const autoSaveTimer = setInterval(() => {
The callback runs approximately every 3 seconds.
Step 3: Simulate saving
console.log("Saving data...");
console.log("Data saved successfully.");
In a real application, this could be replaced with an actual database or file-saving operation.
Step 4: Increase the counter
saveCount++;
Step 5: Stop after three saves
if (saveCount > 3) {
clearInterval(autoSaveTimer);
}
Key Takeaways
- Node.js provides built-in timer functions for scheduling code.
setTimeout()runs a callback after a delay.setInterval()repeatedly runs a callback at an interval.clearTimeout()cancels a scheduledsetTimeout().clearInterval()stops a running interval.setImmediate()schedules a callback for the event loop’s check phase.clearImmediate()cancels asetImmediate()callback.- Timer delays are measured in milliseconds.
1000milliseconds is approximately 1 second.- A timer delay is not an exact guarantee of when the callback will execute.
- Node.js timers work together with the event loop.
setInterval()should be stopped when it is no longer needed.- Countdown timers can be created using
setInterval(). setTimeout()can be used to create delayed tasks.- A timer can be wrapped inside a Promise and used with
async/await. - Timers are useful for reminders, polling, repeated jobs, countdowns, delays, and automation.
- Timer callbacks should avoid unnecessarily long synchronous operations because they can delay other work in the event loop.
- Understanding timers helps you understand the Node.js event loop and asynchronous programming.
FAQs
1. What are timers in Node.js?
Timers are Node.js functions that allow you to schedule JavaScript code to execute after a delay or repeatedly at an interval.
Common timer functions include:
setTimeout()
setInterval()
setImmediate()
Node.js also provides corresponding functions for cancelling scheduled callbacks.
2. What is the difference between setTimeout() and setInterval()?
setTimeout() normally executes its callback once after the specified delay:
setTimeout(() => {
console.log("Hello");
}, 2000);
setInterval() repeatedly executes its callback:
setInterval(() => {
console.log("Hello");
}, 2000);
Use setTimeout() for one-time delayed tasks and setInterval() for repeated tasks.
3. How do I stop a setInterval() timer?
Store the timer returned by setInterval() and pass it to clearInterval().
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
clearInterval(timer);
This stops future executions of that interval.
4. How do I cancel a setTimeout()?
Store the timer returned by setTimeout() and use clearTimeout().
const timer = setTimeout(() => {
console.log("Hello");
}, 5000);
clearTimeout(timer);
The scheduled callback will be cancelled if it has not already executed.
5. What is setImmediate() in Node.js?
setImmediate() schedules a callback to execute during the event loop’s check phase.
Example:
setImmediate(() => {
console.log("Immediate callback");
});
It is different from setTimeout(), and the exact execution order between timers and setImmediate() can depend on the context in which they are scheduled.
6. Are Node.js timer delays exact?
No.
For example:
setTimeout(() => {
console.log("Hello");
}, 1000);
does not guarantee that the callback will execute exactly 1000 milliseconds later.
The 1000 milliseconds represents the minimum delay before the callback becomes eligible to run. The event loop and other work can affect when it actually executes.
7. Can I use Node.js timers with async/await?
Yes.
A timer can be wrapped in a Promise:
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
Then use:
async function start() {
await delay(2000);
console.log("Finished");
}
start();
This is a convenient way to create delays in Promise-based Node.js code.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
