Many applications need to execute tasks after a certain delay or repeatedly at regular intervals.
For example:
- Sending OTPs after a delay
- Refreshing cached data every few minutes
- Displaying countdown timers
- Running scheduled background tasks
- Delaying API requests
- Polling a server for updates
Node.js provides built-in timer functions that make these tasks easy.
The best part?
You don't need to install any package.
In this article, we'll explore the most commonly used timer functions in Node.js:
setTimeout()clearTimeout()setInterval()clearInterval()setImmediate()clearImmediate()
By the end of this article, you'll know when and how to use each timer function effectively.
Let's get started!
What is the Timers Module?
The Timers module provides functions that allow you to schedule code execution in the future.
Although Node.js internally has a Timers module, the commonly used timer functions are available globally, which means you don't need to import anything.
You can directly use:
setTimeout();
setInterval();
setImmediate();
These functions are part of the Node.js runtime and are also available in browsers, although Node.js has its own implementation.
Why Do We Need Timers?
Imagine you're building a chat application.
You may need to:
- Remove inactive users after 30 minutes.
- Refresh online users every 10 seconds.
- Delay sending notifications.
- Retry failed API requests.
- Execute cleanup tasks after a request completes.
Timer functions make these tasks simple.
Understanding setTimeout()
What is setTimeout()?
setTimeout() executes a function once after a specified delay.
Syntax
setTimeout(callback, delay);
- callback → Function to execute.
- delay → Time in milliseconds.
1000 milliseconds = 1 second
Step 1: Print a Message After 3 Seconds
Create a file named:
timeout.js
Add the following code:
console.log("Program Started");
setTimeout(() => {
console.log("Hello after 3 seconds!");
}, 3000);
console.log("Program Finished");
Run the application:
node timeout.js
Output:
Program Started
Program Finished
(After 3 seconds...)
Hello after 3 seconds!
Explanation
Node.js does not pause the program for 3 seconds.
Instead, it schedules the callback and continues executing the remaining code.
After 3 seconds, the callback is executed.
Another Example
setTimeout(() => {
console.log("Welcome to Node.js");
}, 2000);
Output after 2 seconds:
Welcome to Node.js
Real-World Example
Suppose you want to remind a user after 5 seconds.
setTimeout(() => {
console.log("Don't forget to save your changes!");
}, 5000);
Understanding clearTimeout()
What is clearTimeout()?
Sometimes you schedule a timeout but later decide you no longer need it.
clearTimeout() cancels a scheduled timeout before it executes.
Step 1: Store the Timer
const timer = setTimeout(() => {
console.log("This message will never appear.");
}, 5000);
clearTimeout(timer);
console.log("Timeout Cancelled");
Output:
Timeout Cancelled
The callback never executes because it was cancelled.
Real-World Example
Imagine a user is typing in a search box.
Every keystroke schedules a search after 500 milliseconds.
If the user types again before 500 milliseconds, the previous timeout is cancelled.
This technique is called debouncing.
Understanding setInterval()
What is setInterval()?
setInterval() executes a function repeatedly at fixed intervals until it's stopped.
Syntax
setInterval(callback, delay);
Step 1: Print Every 2 Seconds
Create:
interval.js
Add:
setInterval(() => {
console.log("Hello Node.js");
}, 2000);
Run:
node interval.js
Output:
Hello Node.js
(After 2 seconds)
Hello Node.js
(After another 2 seconds)
Hello Node.js
...
The message continues indefinitely.
Real-World Example
Refresh dashboard data every 10 seconds.
setInterval(() => {
console.log("Fetching latest dashboard data...");
}, 10000);
Understanding clearInterval()
What is clearInterval()?
clearInterval() stops an interval.
Step 1: Stop After 5 Executions
let count = 0;
const timer = setInterval(() => {
count++;
console.log(`Execution ${count}`);
if (count === 5) {
clearInterval(timer);
console.log("Interval Stopped");
}
}, 1000);
Output:
Execution 1
Execution 2
Execution 3
Execution 4
Execution 5
Interval Stopped
The interval automatically stops after the fifth execution.
Build a Countdown Timer
let seconds = 10;
const timer = setInterval(() => {
console.log(seconds);
seconds--;
if (seconds < 0) {
clearInterval(timer);
console.log("Time's Up!");
}
}, 1000);
Output:
10
9
8
7
6
5
4
3
2
1
0
Time's Up!
Understanding setImmediate()
What is setImmediate()?
setImmediate() schedules a callback to run after the current event loop phase completes, but before additional timers are processed.
Unlike setTimeout(), you don't specify a delay.
Syntax
setImmediate(callback);
Example
console.log("Start");
setImmediate(() => {
console.log("Inside setImmediate()");
});
console.log("End");
Output:
Start
End
Inside setImmediate()
Explanation
The callback is queued and runs after the current synchronous code has finished executing.
Understanding clearImmediate()
Just like the other timer functions, setImmediate() can also be cancelled.
const immediate = setImmediate(() => {
console.log("This won't execute.");
});
clearImmediate(immediate);
console.log("Immediate Cancelled");
Output:
Immediate Cancelled
Difference Between setTimeout() and setImmediate()
Consider this example:
setTimeout(() => {
console.log("setTimeout");
}, 0);
setImmediate(() => {
console.log("setImmediate");
});
You might expect setTimeout() to always execute first because its delay is 0.
However, the execution order is not guaranteed at the top level of a script.
Depending on the operating system and runtime conditions, either callback may execute first.
If both are scheduled inside an I/O callback, setImmediate() is generally executed before setTimeout(..., 0).
The important takeaway is:
setTimeout()schedules execution after at least the specified delay.setImmediate()schedules execution for the next iteration of the event loop after the current phase.
Build a Reminder Application
console.log("Reminder Scheduled...");
setTimeout(() => {
console.log("Take a short break!");
}, 5000);
Output:
Reminder Scheduled...
(After 5 seconds)
Take a short break!
Build a Clock
setInterval(() => {
console.log(new Date().toLocaleTimeString());
}, 1000);
Output:
10:30:01 PM
10:30:02 PM
10:30:03 PM
...
This is similar to how digital clocks update every second.
Comparison of Timer Functions
setTimeout() - Executes a function once after a delay
clearTimeout() - Cancels a scheduled timeout
setInterval() - Executes a function repeatedly
clearInterval() - Stops an interval
setImmediate() - Executes a callback on the next event loop iteration
clearImmediate() - Cancels a scheduled immediate callback
Best Practices
When using timers in Node.js:
- Always clear intervals that are no longer needed.
- Avoid creating unnecessary intervals, as they consume resources.
- Use
setTimeout()for one-time delayed tasks. - Use
setInterval()only for tasks that genuinely need to repeat. - Prefer recursive
setTimeout()instead ofsetInterval()when the next execution depends on the previous one completing (for example, polling an API).
Example of recursive setTimeout():
function fetchData() {
console.log("Fetching data...");
setTimeout(fetchData, 5000);
}
fetchData();
This avoids overlapping executions if a task takes longer than expected.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Forgetting to stop intervals with
clearInterval(). - Assuming
setTimeout()blocks the execution of the program. - Using
setInterval()for long-running tasks that may overlap. - Expecting
setTimeout(..., 0)to execute immediately. - Assuming
setImmediate()andsetTimeout(..., 0)always execute in the same order.
Final Thoughts
Timers are one of the most frequently used features in Node.js. They allow you to schedule tasks, create polling mechanisms, build countdowns, refresh data, and delay operations without blocking the event loop.
In this article, you learned:
- What the Timers module is
- How
setTimeout()works - How to cancel timeouts with
clearTimeout() - How to execute repeating tasks using
setInterval() - How to stop intervals using
clearInterval() - How
setImmediate()differs fromsetTimeout() - Practical examples and best practices
As you continue learning Node.js, you'll use timer functions in background jobs, schedulers, retry mechanisms, rate limiting, caching, and many other real-world scenarios.
Happy Coding! 🚀