Consider the following JavaScript code. What will be printed to the console?
console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End');
Remember that Promise callbacks go to the microtask queue, which runs before the macrotask queue where setTimeout callbacks go.
The synchronous console.log calls run first: 'Start' then 'End'. The Promise callback runs next because microtasks have priority, printing 'Promise'. Finally, the setTimeout callback runs, printing 'Timeout'.
Analyze the following code and select the correct console output.
console.log('1'); setTimeout(() => console.log('2'), 100); setTimeout(() => console.log('3'), 0); Promise.resolve().then(() => console.log('4')); console.log('5');
Microtasks run before any timers, even if the timer delay is zero.
First, synchronous logs '1' and '5'. Then microtask logs '4'. Then timers with 0ms delay logs '3', and finally timer with 100ms delay logs '2'.
Look at this code with nested setTimeout and Promise. What will it print?
console.log('A'); setTimeout(() => { console.log('B'); Promise.resolve().then(() => console.log('C')); }, 0); Promise.resolve().then(() => { console.log('D'); setTimeout(() => console.log('E'), 0); }); console.log('F');
Remember microtasks run immediately after the current task, before the next macrotask.
First synchronous logs 'A' and 'F'. Then microtask logs 'D' and schedules a timer for 'E'. Next macrotask logs 'B' and schedules a microtask for 'C'. That microtask runs immediately after 'B', printing 'C'. Finally, the timer for 'E' runs.
Consider this code snippet. What error will it raise when run?
setTimeout(() => { throw new Error('Oops'); }, 0); Promise.reject('Fail').catch(e => console.log('Caught:', e));
Errors thrown inside setTimeout callbacks are not caught by Promise.catch.
The Promise.reject is caught and logs 'Caught: Fail'. The error thrown inside setTimeout is asynchronous and not caught here, so it causes an uncaught error in the environment but does not affect this output.
Which of the following lists the correct order of event loop phases in Node.js?
Recall the Node.js event loop phases as documented in official docs.
The Node.js event loop phases run in this order: Timers, Pending callbacks, Idle/prepare, Poll, Check, and Close callbacks.