Explain the order of execution for the following JavaScript code snippet.
š” Model Answer
When the script runs, the synchronous code executes first: console.log('Start') and console.log('End') are printed immediately. The setTimeout callbacks are queued as macrotasks, and the Promise callbacks are queued as microtasks. After the synchronous code finishes, the event loop processes microtasks before macrotasks. Thus, Promise.resolve().then(...) runs, printing 'Promise 1', then the chained .then prints 'Promise 2'. Once the microtask queue is empty, the event loop picks the first macrotask, executing the first setTimeout callback and printing 'Timeout 1'. Finally, the second setTimeout callback runs, printing 'Timeout 2'. The final output order is: Start, End, Promise 1, Promise 2, Timeout 1, Timeout 2.
This answer was generated by AI for study purposes. Use it as a starting point ā personalize it with your own experience.
š¤ Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI ā Starts at ā¹500