简体   繁体   中英

DOM events priority in the event queue

Suppose I have this code:

$('button').click(function onClick() {
    $('#divResult').text(Math.rand());
});

setInterval(function timeout() {
    console.log("Hello");
}, 300);

setInterval(function timeout() {
     console.log("Hi");
}, 200);

setInterval(function timeout() {
    console.log("Yo!");
}, 100);

So basically, after 300ms, I'll have more than 1 callback function in the event queue. Now, let's say that after some period, a user clicks on something. This click event gets processed and the callback function onClick() goes inside the event queue too. Let's say the first time it goes there, there are already 2 callback functions created by setInterval. Since this is a DOM-related function which will do re-rendering of the window, will it have priority over these functions?

In this talk on event loops , the author mentions a render queue which is given a priority over the callback queue (where callbacks by methods like setTimeout and setInterval go). Since onClick() does things related to rendering, will it go into this queue or into the regular callback queue and wait for its turn?

Well I think I'll give it a shot, but this info is pretty new to me as well.

Since this is a DOM-related function which will do re-rendering of the window, will it have priority over these functions?

No, I don't believe that function itself will have any more priority than the functions inside of those intervals. I don't think that the browser itself will know that the click callback will actually change the DOM. After the callback function runs and the element's text changes, then the browser will repaint that node when it has a chance.

Since onClick() does things related to rendering, will it go into this queue or into the regular callback queue and wait for its turn?

I don't believe the onclick handler has to do anything related to rendering. Yes, most of the time we code it to, but I don't think it always has to change an element's appearance. It could just send an Ajax request in the background. It could just log something to the console. You never really know.

Also keep in mind that setInterval doesn't add an event onto the event queue to execute at a certain time later. It waits a certain time and then adds that event onto the event queue. You can read more on that here .

Hopefully I didn't make a fool of myself since I really didn't start diving deep into JS until a few months ago. If I'm off about anything let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM