Reputation: 341
Javascript operates on a synchronous single main thread. and via the eventloop it waits for new microtask/ macrotask that browser's internal web api returns back to us. I have seen examples of fetch, xhr, I was wondering is this also the case with DOM listening for user actions. Since I cannot picture how a single thread can listen to user input but not block the rest of the JavaScript on the webpage.
Here I make the generalization from what I understand of fetch and xhr, i know the network http requests are operating on a separate thread and the internal browser binding helps webapi returns a task to micro/macro task queue for the next event loop to detect (when the stack is clear).
or another example, like setTimeout returns to the macrotask queue. but the timekeeping is never on the javascript thread.
Upvotes: 2
Views: 352
Reputation: 462
The DOM is a Web API as well and not part of JS. When an event fires from a DOM element that you have attached a listener to (clicking a button you've attached a listener to for example) it will place that listener's callback in the appropriate Queue to be processed by the JS Stack, therefore never entering the queue until the DOM element has been clicked. With this you could have dozens/n
number of listeners that the DOM Web API is handling which won't block the single JS thread or enter the queue unless they are specifically interacted with.
If an event fires from a DOM element but it does not have a listener attached nothing will happen on the stack as no callback will be entering your queue.
Upvotes: 1