Node.js provides several timer functions for scheduling code execution. Here's how they work.
setTimeout#
setInterval#
setImmediate#
process.nextTick#
Timer Promises (Node.js 16+)#
Event Loop Phases#
Patterns#
Timer References#
Scheduling Patterns#
Common Mistakes#
Best Practices#
Choosing Timers:
✓ setTimeout for delayed execution
✓ setInterval for repeated tasks
✓ setImmediate after I/O
✓ process.nextTick for immediate async
Memory Management:
✓ Always clear timers when done
✓ Use unref() for non-critical timers
✓ Store timer IDs for cleanup
✓ Clear on process exit
Patterns:
✓ Use timer promises in Node 16+
✓ Implement debounce/throttle
✓ Add timeout to async operations
✓ Yield with setImmediate in loops
Avoid:
✗ Recursive process.nextTick
✗ Relying on timer order
✗ Forgetting to clear intervals
✗ Assuming timer precision
Conclusion#
Node.js timers provide flexible scheduling options. Use setTimeout for delays, setInterval for repetition, setImmediate for post-I/O execution, and process.nextTick for immediate callbacks. The timer promises API in Node.js 16+ makes async timer code cleaner. Always clean up timers to prevent memory leaks.