Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event loop does NOT "run to completion"

According to MDN, messages in the JavaScript event loop "run to completion".
(https://developer.mozilla.org/docs/Web/JavaScript/Event_loop#run-to-completion)

But I have created a case where this does not seem to happen.

abortController1 = new AbortController()
abortController2 = new AbortController()

abortController1.signal.addEventListener("abort", () =>
{
    console.log("abort 1 start")
    abortController2.abort()
    console.log("abort 1 end")
})

abortController2.signal.addEventListener("abort", () =>
{
    console.log("abort 2")
})

abortController1.abort()

Output:

abort 1 start
abort 2
abort 1 end

I was expecting to see this output:

abort 1 start
abort 1 end
abort 2

Can someone please explain what's going on here?

EDIT (possible clues) -

  • Call to DrainDirectTasks - https://searchfox.org/mozilla-central/rev/94c62970ba2f9c40efd5a4f83a538595425820d9/xpcom/threads/nsThread.cpp#1094
    • https://github.com/mozilla/gecko-dev/blob/26ad7aaffe02c4f9ab84c0faf5bc2f4dc4583806/xpcom/threads/nsThread.cpp#L1094
  • Jobs and Host Operations to Enqueue Jobs - https://tc39.es/ecma262/2020/#sec-jobs
  • MDN docs EventTarget.dispatchEvent() - https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent
    • Blame - https://github.com/mdn/content/blame/06bf946f61297df045fe24f5fba993aa0c312207/files/en-us/web/api/eventtarget/dispatchevent/index.html#L41
like image 963
daka Avatar asked Jun 25 '26 13:06

daka


1 Answers

When an event is triggered directly by code, it runs the listeners synchronously. The MDN documentation for dispatchEvent() explains this:

Unlike "native" events, which are fired by the browser and invoke event handlers asynchronously via the event loop, dispatchEvent() invokes event handlers synchronously. All applicable event handlers are called and return before dispatchEvent() returns.

While this doesn't mention abort() specifically, I see no reason why it wouldn't be treated similarly.

like image 157
Barmar Avatar answered Jun 27 '26 03:06

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!