Performance: Event loop phases and timer execution
MEDIUM IMPACT
This concept affects how quickly Node.js processes timers and callbacks, impacting responsiveness and throughput of server-side applications.
function heavyTask() {
return new Promise(resolve => {
setImmediate(() => {
for(let i = 0; i < 1e8; i++) {}
resolve();
});
});
}
async function runInterval() {
while(true) {
await heavyTask();
console.log('Interval task done');
await new Promise(r => setTimeout(r, 1000));
}
}
runInterval();setInterval(() => {
// heavy synchronous task
for(let i = 0; i < 1e8; i++) {}
console.log('Interval task done');
}, 1000);| Pattern | Event Loop Blocking | Timer Accuracy | CPU Usage | Verdict |
|---|---|---|---|---|
| Heavy synchronous code in setInterval | Blocks event loop for 100+ ms | Timers delayed | High CPU spikes | [X] Bad |
| Async heavy task with setImmediate and await | No blocking, event loop free | Timers fire on time | Balanced CPU usage | [OK] Good |