Node.js Timers Module
Node.js'stimersThe module provides a series of functions for executing code after a specified time or at specified intervals repeatedly. These features are very useful for implementing delayed execution, periodic tasks, and timeout control.
Althoughtimersthe module is a core module of Node.js, but its methods such assetTimeout(), setInterval()andsetImmediate()are globally available without explicit import.
Main Timer Functions
setTimeout()
setTimeout()The function is used to execute a callback function once after a specified number of milliseconds.
Example
setTimeout(() => {
console.log('This message will be displayed after 2 seconds');
}, 2000);
Parameter Description
- Callback function: The function to execute
- Delay time: Time in milliseconds (1000 ms = 1 second)
- Optional parameters: Additional parameters passed to the callback function
Example
setTimeout((name, age) => {
console.log(`Hello, ${name}, you are ${age}years old`);
}, 1000, 'Zhang San', 25);
clearTimeout()
clearTimeout()Used to cancel a previously setsetTimeout()timer.
Example
console.log('This message will not be displayed');
}, 2000);
clearTimeout(timerId); // Cancel the timer
setInterval()
setInterval()The function is used to repeatedly execute a callback function at specified millisecond intervals.
Example
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`This is the ${counter}execution`);
if (counter === 5) {
clearInterval(intervalId); // Stop the timer
}
}, 1000);
clearInterval()
clearInterval()Used to stop a previously setsetInterval()repeating timer.
Example
console.log('This message will be displayed repeatedly');
}, 1000);
// Stop the timer after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 5000);
setImmediate()
setImmediate()The function is used to execute a callback function at the end of the current event loop.
Example
setImmediate(() => {
console.log('Callback executed immediately');
});
console.log('End');
// Output order:
// Start
// End
// Callback executed immediately
clearImmediate()
clearImmediate()Used to cancel a previously setsetImmediate()immediate callback.
Example
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. The following is the execution order of several timers:
- Synchronous code: Executed first
- process.nextTick(): Executed immediately after the current phase ends
- Promise callbacks: Microtask queue
- setImmediate(): Executed after I/O callbacks
- setTimeout() and setInterval(): Executed in the check phase
Example
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
Canceling Timers
All timer functions return anTimeoutobject, which can be used to cancel the timer. It is safe to call the cancel function even if the timer has already executed.
Example
clearTimeout(timeout); // Safe to call even if the timer has executed
Timer Accuracy
Node.js timers do not guarantee precise execution time; they represent a minimum waiting time. System load and other factors may affect the actual execution time.
Memory Leaks
Forgetting to clearsetInterval()timers is a common source of memory leaks. Make sure to clear timers when they are no longer needed.
Example
setInterval(() => {
// Perform some operation
}, 1000);
// Correct approach - clear the timer at an 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 time each time, using recursivesetTimeoutComparesetIntervalis more reliable.
Example
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
let current = seconds;
console.log(`Countdown starts: ${current}seconds`);
const timer = setInterval(() => {
current--;
if (current <= 0) {
clearInterval(timer);
console.log('Countdown ended!');
} else {
console.log(`Remaining time: ${current}seconds`);
}
}, 1000);
}
countdown(5);
Request Timeout Handling
Example
return new Promise((resolve, reject) => {
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'stimersmodule, you can effectively control the execution timing of code and implement various scheduled tasks and asynchronous control flows.
Node.js Built-in Modules