setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));What is the most likely output order when this code runs?
setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate'));
In Node.js, setTimeout callbacks with 0 delay run in the timers phase, which happens before the check phase where setImmediate callbacks run. So timeout logs before immediate.
process.nextTick inside a setTimeout callback?setTimeout(() => {
console.log('timeout');
process.nextTick(() => console.log('nextTick inside timeout'));
}, 0);What will be the output order?
setTimeout(() => {
console.log('timeout');
process.nextTick(() => console.log('nextTick inside timeout'));
}, 0);process.nextTick callbacks run immediately after the current operation completes, before the event loop continues. So inside the setTimeout callback, timeout logs first, then the nextTick callback runs.
setTimeout(() => console.log('Hello'), '1000');setTimeout(() => console.log('Hello'), '1000');
Node.js converts string delays to numbers automatically, so no error occurs. The callback runs after approximately 1 second.
let count = 0;
setInterval(() => {
if (count === 3) clearInterval();
console.log(count);
count++;
}, 1000);
Why does the interval never stop?
let count = 0; const intervalId = setInterval(() => { if (count === 3) clearInterval(intervalId); console.log(count); count++; }, 1000);
clearInterval requires the interval ID returned by setInterval. Calling it without arguments does nothing, so the interval keeps running.
console.log('start');
setTimeout(() => {
console.log('timeout 1');
process.nextTick(() => console.log('nextTick inside timeout 1'));
}, 0);
setImmediate(() => {
console.log('immediate 1');
setTimeout(() => console.log('timeout 2'), 0);
});
process.nextTick(() => console.log('nextTick 1'));
console.log('end');console.log('start'); setTimeout(() => { console.log('timeout 1'); process.nextTick(() => console.log('nextTick inside timeout 1')); }, 0); setImmediate(() => { console.log('immediate 1'); setTimeout(() => console.log('timeout 2'), 0); }); process.nextTick(() => console.log('nextTick 1')); console.log('end');
Execution order:
1. 'start' and 'end' log immediately.
2. After main script completes (end of poll phase), process.nextTick callbacks run: 'nextTick 1' logs.
3. Check phase runs: 'immediate 1' logs, schedules 'timeout 2'.
4. Timers phase (next iteration): 'timeout 1' logs.
5. After 'timeout 1' callback, process.nextTick runs: 'nextTick inside timeout 1' logs.
6. Next timers phase: 'timeout 2' logs.