setTimeout() and setInterval() in Node.js
JavaScript provides timer functions to execute code after a delay
or repeatedly at a specified interval. The two commonly used timer
functions are setTimeout() and setInterval().
1. Introduction to Timer Functions
Imagine Samadhan is studying Node.js at CIIT Training Institute. He wants to display a reminder after three seconds. Pradnya wants to display a message repeatedly every two seconds. JavaScript timer functions can handle both requirements.
setTimeout() means execute once after a delay.
setInterval() means execute repeatedly at an interval.
2. What is setTimeout()?
The setTimeout() function schedules a callback to run
after a specified delay in milliseconds.
It does not guarantee execution at the exact requested time.
Syntax
setTimeout(callback, delayInMilliseconds);
| Parameter | Description |
|---|---|
callback |
The function to execute after the delay. |
delayInMilliseconds |
The minimum delay before the callback becomes eligible to run. |
3. Example of setTimeout()
Samadhan wants to display a welcome message after three seconds.
console.log("Samadhan started learning Node.js.");
setTimeout(() => {
console.log("Welcome to CIIT Training Institute!");
}, 3000);
console.log("Samadhan is practicing JavaScript.");
Output
Samadhan started learning Node.js. Samadhan is practicing JavaScript. Welcome to CIIT Training Institute!The last message becomes eligible to execute after approximately three seconds.
Explanation
- The first
console.log()displays the starting message. setTimeout()schedules its callback for approximately three seconds later.- JavaScript continues executing the next statement without waiting for the timer.
- After the delay, the callback runs when the event loop can process it.
4. setTimeout() Execution Flow
5. What is setInterval()?
The setInterval() function repeatedly schedules a
callback at a specified interval until the interval is cancelled
or the program stops.
Syntax
setInterval(callback, intervalInMilliseconds);
For example, an interval of 2000 milliseconds requests repeated execution approximately every two seconds.
6. Example of setInterval()
Pradnya wants to display a practice reminder every two seconds.
We can use setInterval() for this task.
let count = 1;
const timer = setInterval(() => {
console.log("Pradnya is practicing Node.js: " + count);
count++;
if (count > 3) {
clearInterval(timer);
console.log("Practice reminder completed.");
}
}, 2000);
Output
Pradnya is practicing Node.js: 1 Pradnya is practicing Node.js: 2 Pradnya is practicing Node.js: 3 Practice reminder completed.Each reminder is requested approximately two seconds apart.
Explanation
countstarts at 1.setInterval()schedules the callback repeatedly.- Each execution displays the current count and increments it.
- When the count becomes greater than 3,
clearInterval(timer)stops future interval callbacks. - The completion message is displayed after the third reminder.
7. setInterval() Execution Flow
8. Using clearTimeout()
The clearTimeout() function cancels a scheduled timeout
callback if it has not already started executing.
const timer = setTimeout(() => {
console.log("This message will not appear.");
}, 3000);
clearTimeout(timer);
console.log("Timeout cancelled.");
Output
Timeout cancelled.
The timeout is cancelled before its callback runs, so the scheduled message is not displayed.
9. Using clearInterval()
The clearInterval() function cancels future executions
of an interval timer.
let count = 0;
const timer = setInterval(() => {
count++;
console.log("Count: " + count);
if (count === 3) {
clearInterval(timer);
console.log("Interval stopped.");
}
}, 1000);
Output
Count: 1 Count: 2 Count: 3 Interval stopped.
10. Difference between setTimeout() and setInterval()
| setTimeout() | setInterval() |
|---|---|
| Schedules a callback to run once after a delay. | Schedules a callback to run repeatedly. |
| Uses a delay in milliseconds. | Uses an interval in milliseconds. |
Cancelled using clearTimeout(). |
Cancelled using clearInterval(). |
| Useful for delayed messages and one-time actions. | Useful for repeated reminders and periodic tasks. |
| Normally invokes its callback once. | Continues until cancelled or the runtime stops. |
11. Real-World Example: Course Reminder
At CIIT Training Institute, Samadhan wants to show a welcome message after a delay, while Pradnya wants to display a limited number of reminders.
// One-time welcome message
setTimeout(() => {
console.log("Welcome, Samadhan!");
}, 1000);
// Repeated reminders
let reminderCount = 0;
const reminderTimer = setInterval(() => {
reminderCount++;
console.log("Pradnya: Remember to practice JavaScript.");
if (reminderCount === 2) {
clearInterval(reminderTimer);
console.log("Pradnya's reminders are complete.");
}
}, 2000);
Expected Output
Welcome, Samadhan! Pradnya: Remember to practice JavaScript. Pradnya: Remember to practice JavaScript. Pradnya's reminders are complete.The welcome message is scheduled after one second. The reminders are scheduled approximately two seconds apart.
12. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Assuming a timer executes at the exact requested time. | Remember that the delay is a minimum waiting period, not an exact execution guarantee. |
| Forgetting to stop a repeating interval. | Use clearInterval() when repetition is no longer required. |
Calling clearTimeout() after the callback has already run. |
Cancel the timeout before its callback begins if cancellation is needed. |
Using setInterval() for every repeated asynchronous task. |
Consider recursive setTimeout() when each task must finish before the next one is scheduled. |
13. Important Points to Remember
setTimeout()schedules a callback after a delay.setInterval()schedules repeated callback execution.- Timer delays are measured in milliseconds.
clearTimeout()cancels a pending timeout.clearInterval()stops future interval callbacks.- Timer callbacks run when the event loop can process them.
- Timers do not block the entire JavaScript program while waiting.
Summary
In this lesson, we learned how setTimeout() schedules a callback after a delay and how setInterval() schedules repeated callbacks. We also learned to cancel timers using clearTimeout() and clearInterval(), understand timer execution flow, and apply timer functions to practical examples involving Samadhan, Pradnya, and CIIT Training Institute.