Performance: Event loop phases and timer execution
This concept affects how quickly Node.js processes timers and callbacks, impacting responsiveness and throughput of server-side applications.
Jump into concepts and practice - no test required
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 |
setTimeout callbacks?setTimeout and setInterval.console.log('Start');
setTimeout(() => console.log('Timeout 1'), 0);
setTimeout(() => console.log('Timeout 2'), 10);
console.log('End');setTimeout(console.log('Hello'), 1000);console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
What is the correct order of output?