1

Excerpt from the book "Secrets of a Javascript Ninja" :

EVENTS ARE ASYNCHRONOUS

Events, when they happen, can occur at unpredictable times and in an unpredictable order (it’s tricky to force users to press keys or click in some particular order). We say that the handling of events, and therefore the invocation of their handling functions, is asynchronous.

The following types of events can occur, among others:

■ Browser events, such as when a page is finished loading or when it’s to be unloaded

■ Network events, such as responses coming from the server (Ajax events, serverside events)

■ User events, such as mouse clicks, mouse moves, and key presses

■ Timer events, such as when a timeout expires or an interval fires

Are all these above events handled by same queue in the event loop? I got this doubt while trying to test a DOM click event in a script :

<html>

<body>
    <button id="bId">A button</button>

</body>
<script>
    function testing() {
        document.getElementById('bId').addEventListener("click", function () {
            console.log('clicked');
        })
        console.log('before click');
        document.getElementById('bId').click();
        console.log('after click')
    };
    testing();
</script>

</html>

As i understand, any asynchronous events (like timer, promises) using the event loop queue will wait for call stack to be empty.

In the above code if the DOM events were using the event loop queue shouldn't the output clicked be printed after the before click and after click console.log() function calls?

Are there separate types of queues for different kinds of events?

3
  • There are, but that doesn't really matter. In this case, the event is fired synchronously as said by the current answer. Also, Promises are different than events, they're microtasks and thus won't wait the event loop to be free, you can freeze the event loop with recursive Promises. Commented Oct 15, 2019 at 12:27
  • @Kaiido so only setTimeout and setInterval wait for call stack to be free? Not even the callbacks or promises? Commented Oct 15, 2019 at 14:17
  • No that's not what I meant. Some events are fired synchronously, most aren't. It's not really their Event nature that matters but how they got fired. You'd have to go through the specs to see how they get fired in each cases. When the specs ask to queue a task, then it will wait for what's currently on the call stack to be emptied, when it asks to queue a microtask, then it's just waiting for the end of the current task, when it asks to fire an event it's synchronous. Once again most of the time events are coming from "queue a task to fire an event" (async). Just like timers btw. Commented Oct 15, 2019 at 15:19

1 Answer 1

2

I thought this might help, but it also prints in the order of click called directly, it looks they are same.

This is what mdn has to say:

Dispatches an Event at the specified EventTarget, (synchronously) invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

But I am pretty sure this is not the case when the element is physically clicked by the user.

<html>

<body>
    <button id="bId">A button</button>

</body>
<script>
    function testing() {
        document.getElementById('bId').addEventListener("click", function () {
            console.log('clicked');
        })
        console.log('before click');

        var el = document.getElementById('bId');
        var event;
        if (window.CustomEvent) {
           event = new CustomEvent('click');
        } else {
           event = document.createEvent('click');
           event.initCustomEvent('click', true, true);
        }
        el.dispatchEvent(event);
        console.log('after click')
    };
    testing();
</script>

</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes OP's quote is misleading, all events are not fired asynchronously, EventTarget.dispatchEvent is synchronous and DOM methods that do collaterally fire events also fire it synchronously ( HTMLElement.click, FormElement.reportValidity etc.)
@Kaiido that's not my qoute. Taken from a book which seems credible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.