Web Technology Basics

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

When the JavaScript above is run in a browser, which of the following is the order in which the characters are shown on the console?

  1. AA → B → C → D
  2. BA → D → B → C
  3. CA → D → C → B
Show answer and explanation

Answer: C. A → D → C → B

A page's JavaScript runs on a single main thread, and no other work cuts in until the currently running code finishes. First, all the synchronous code runs, showing A and D. The function passed to the Promise's then runs as a microtask immediately after the current code finishes, so C is shown next. Even with 0 ms given to setTimeout, its function is put into the queue as a task, and the event loop takes it out only after the microtasks are done, so B comes last.

  • A. Functions passed to setTimeout or then are not run on the spot; they run after the synchronous code finishes.
  • B. Promise callbacks (microtasks) run before setTimeout callbacks (tasks).
  • C. Correct. The order is the synchronous A and D, then the microtask C, then the task B.
Practice this topic Back to topic

Books on Web Technology Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Web Technology Basics questions

  1. Under the browser's same-origin policy, which of the following URLs is considered to have the same origin as https://www.example.com/app/index.html?
  2. JavaScript on a page at https://app.example.com uses fetch to send a POST request with a body of Content-Type application/json to https://api.example.net/orders. Which of the following correctly describes how CORS behaves in this case?
  3. Which of the following correctly describes a Service Worker?
  4. For a page with responsive design that also supports smartphones, which of the following is the main purpose of writing <meta name="viewport" content="width=device-width, initial-scale=1"> in <head>?
  5. The response for a "my page" whose content differs for each user is given Cache-Control: private, max-age=60. Which of the following correctly describes the effect of this setting?