Node.js — Timers
setTimeout
setTimeout(() => {
console.log('Executed after 1 second');
}, 1000);
const id = setTimeout(fn, delay);
clearTimeout(id); // Cancel
setInterval
let count = 0;
const interval = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count >= 5) clearInterval(interval);
}, 1000);
setImmediate
setImmediate(() => {
console.log('Executes after current event loop');
});
process.nextTick
process.nextTick(() => {
console.log('Executes before next event loop');
});
Timer Comparison
| Function | When it runs |
|---|---|
| setTimeout(fn, 0) | Next event loop iteration |
| setImmediate(fn) | After I/O callbacks |
| process.nextTick(fn) | Before next event loop |
Practical Example
// Debounce
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// Throttle
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Mini Practice
- Use setTimeout for delays
- Use setInterval for intervals
- Cancel a timer
- Implement debounce
Up Next
Continue with Processes — managing child processes.
Related Topics
Frequently Asked Questions about Timers
What is Timers in Node.js?
Timers is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Timers?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Timers.
Why is Timers important in Node.js?
Timers is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.