Guess the output #2
Question:
console.log("start");
setTimeout(() => {
console.log("setTimeout");
});
Promise.resolve().then(() => {
console.log("resolve");
});
console.log("end");
Output:
start
end
resolve
setTimeout
Explanation:
- console.log("start");: This line is executed immediately, so start is printed first.
- setTimeout(() => { console.log("setTimeout"); });: The callback inside setTimeout is scheduled to run after the current event loop finishes, putting it into the macrotask queue. Thus, setTimeout is delayed.
- Promise.resolve().then(() => { console.log("resolve"); });: This creates a microtask that will be executed after the current synchronous code finishes, but before any macrotasks. Therefore, resolve is logged before setTimeout.
- console.log("end");: This line is executed immediately after the first log, so end is printed second.