JavaScript: How is callback execution strategy for promises different than DOM events callback?

Jitendra Kasaudhan
10 min readMay 4, 2018

As a JavaScript developer, first of all, I thought, why the heck do I need to understand the internals of browsers with respect to JavaScript? Sometimes I have been through a situation like “WHAT?? THIS IS STRANGE!!” but later on after diving deeper into the subject matter, I realized that it’s important to understand a bit of how browser and JS engine work together. I hope this article will provide a bit of guidance to predict the correct behavior of your JS code and minimize strange situations.

Basically, this article covers following sub topics

  1. Quiz to predict the output of the sample JS code.
  2. An overview of browser, event loop, JS engine, event loop queues.
  3. How browser executes DOM events(click, http requests) and its callback?
  4. How is callback execution strategy for promises different than DOM events callback?
  5. Different execution strategy of tasks queued in Task queue and Micro task queue.
  6. What kind of tasks are queued in Task queue and Micro task queue?
  7. Conclusion (Answers to the quiz).

……………………………………………………………………………………

  1. Quiz to predict the output of the sample JS code
    Test 1:
    What would be the sequence of log messages of following JS code?
    Running example can be found here .

Test 2: We have a button with two click event listeners on the same button as shown in the code sample below.

Running example can be found here . Please try to predict the order of log messages when a button is clicked?

If we have correct versions of browsers, output of the above code samples are as follow

Test 1: Start, End, Promise 1, Promise 2, Settimeout 1, Settimeout 2

--

--