Nodejs Timers Module
[Node.js Built-in Modules](#)
* * *
Node.js's `timers` module provides a set of functions for executing code after a specific time or repeatedly executing code at specified intervals. These functions are very useful for implementing delayed execution, periodic tasks, and timeout control.
Although the `timers` module is a core module of Node.js, its methods such as `setTimeout()`, `setInterval()`, and `setImmediate()` are globally available and do not require explicit import.
* * *
## Main Timer Functions
### setTimeout()
The `setTimeout()` function is used to execute a callback function once after the specified number of milliseconds.
## Example
// Print message after 2 seconds
setTimeout(()=>{
console.log('This message will be displayed after 2 seconds');
},2000);
#### Parameter Description
1. **Callback function**: The function to execute
2. **Delay time**: Time in milliseconds (1000 milliseconds = 1 second)
3. **Optional parameters**: Additional parameters passed to the callback function
## Example
// Example with additional parameters
setTimeout((name, age)=>{
console.log(`Hello, ${name}, you are ${age} years old`);
},1000,'Zhang San',25);
### clearTimeout()
`clearTimeout()` is used to cancel a timer previously set by `setTimeout()`.
## Example
const timerId = setTimeout(()=>{
console.log('This message will not be displayed');
},2000);
clearTimeout(timerId);// Cancel the timer
* * *
### setInterval()
The `setInterval()` function is used to repeatedly execute a callback function at the specified number of milliseconds.
## Example
// Print message every 1 second
let counter =0;
const intervalId = setInterval(()=>{
counter++;
console.log(`This is execution number ${counter}`);
if(counter ===5){
clearInterval(intervalId);// Stop the timer
}
},1000);
### clearInterval()
`clearInterval()` is used to stop a recurring timer previously set by `setInterval()`.
## Example
const intervalId = setInterval(()=>{
console.log('This message will be displayed repeatedly');
},1000);
// Stop the timer after 5 seconds
setTimeout(()=>{
clearInterval(intervalId);
},5000);
* * *
### setImmediate()
The `setImmediate()` function is used to execute a callback function at the end of the current event loop.
## Example
console.log('Start');
setImmediate(()=>{
console.log('Execute callback immediately');
});
console.log('End');
// Output order:
// Start
// End
// Execute callback immediately
### clearImmediate()
`clearImmediate()` is used to cancel an immediate execution callback previously set by `setImmediate()`.
## Example
const immediateId = setImmediate(()=>{
console.log('This message will not be displayed');
});
clearImmediate(immediateId);
* * *
## Execution Order of Timers
Understanding the Node.js event loop is very important for mastering the execution order of timers. Here is the execution order of several timers:
1. **Synchronous code**: Executes first
2. **process.nextTick()**: Executes immediately after the current phase ends
3. **Promise callbacks**: Microtask queue
4. **setImmediate()**: Executes after I/O callbacks
5. **setTimeout() and setInterval()**: Execute in the check phase
## Example
console.log('Start');
setTimeout(()=> console.log('setTimeout'),0);
setImmediate(()=> console.log('setImmediate'));
process.nextTick(()=> console.log('nextTick'));
Promise.resolve().then(()=> console.log('Promise'));
console.log('End');
// Typical output order:
// Start
// End
// nextTick
// Promise
// setTimeout
// setImmediate
* * *
## Advanced Usage and Notes
### Cancelling Timers
All timer functions return a `Timeout` object that can be used to cancel the timer. It is safe to call the cancel function even if the timer has already executed.
## Example
const timeout = setTimeout(()=>{},1000);
clearTimeout(timeout);// Safe to call even if timer has executed
### Timer Precision
Node.js timers cannot guarantee precise execution time; they represent the "minimum" waiting time. System load and other factors may affect the actual execution time.
### Memory Leaks
Forgetting to clear `setInterval()` timers is a common source of memory leaks. Make sure to clear timers when they are no longer needed.
## Example
// Wrong approach - may cause memory leaks
setInterval(()=>{
// Perform some operation
},1000);
// Correct approach - clear the timer at the appropriate time
const interval = setInterval(()=>{
// Perform some operation
if(someCondition){
clearInterval(interval);
}
},1000);
### Recursive setTimeout Instead of setInterval
For tasks that require a fixed interval but have uncertain execution times each time, using recursive `setTimeout` is more reliable than `setInterval`.
## Example
function doSomething(){
console.log('Executing task...');
// Simulate uncertain task execution time
const delay =Math.random()*1000;
setTimeout(doSomething,1000+ delay);
}
setTimeout(doSomething,1000);
* * *
## Practical Application Examples
### Implementing a Simple Countdown
## Example
function countdown(seconds){
let current = seconds;
console.log(`Countdown started: ${current} seconds`);
const timer = setInterval(()=>{
current--;
if(current {
const timeoutId = setTimeout(()=>{
reject(new Error(`Request timeout (${timeout}ms)`));
}, timeout);
fetch(url)
.then(response =>{
clearTimeout(timeoutId);
resolve(response);
})
.catch(error =>{
clearTimeout(timeoutId);
reject(error);
});
});
}
// Usage example
fetchWithTimeout('https://api.example.com/data')
.then(data => console.log(data))
.catch(error => console.error(error));
By mastering Node.js's `timers` module, you can effectively control the execution timing of your code and implement various timed tasks and asynchronous control flows.
[Node.js Built-in Modules](#)
YouTip