Search code examples
javascriptasynchronouscallstackevent-loop

Does JavaScript have an Event table?


I read an article on Medium that said that "JavaScript has an event table that keeps tracks of all the events that will be executed asynchronously maybe after some time interval or after the resolution of some API requests". It's the first time I heard about it so I decided to research it, but a google search didn't return any results other than that article. I also found the following information online "JavaScript doesn't have an explicit "event table" data structure that stores delayed events. Instead, events and asynchronous tasks are managed through the event queue and timer functions like setTimeout and setInterval". Which one of these is correct? Here's the article


Solution

  • I've never heard the term "event table" until today. No, the JavaScript language does have no such thing, however it does make sense as a structure that could exist in some runtimes.

    an event table that keeps tracks of all the events that will be executed asynchronously

    That's quite wrong, or really sloppy terminology at best:

    • an event is not "executed", it is "fired" or "dispatched". What is executed is a task or an event handler or a callback function
    • an event object is created when it occurs, it is not stored in a table. What could be stored in such a table is the event registration or event handler.

    However, none of the implementations I've come across so far (both browsers and server-side runtimes) has a global "events table" that "keeps tracks of all the events". Instead, event handlers are normally stored in the object on which they were registered. The timer callback is stored in the timer object that setTimeout created. The onload callback is stored in the network request object that fetch created. The onclick callback is stored in the DOM node on which addEventListener('click') was called.

    Admittedly, the runtimes will have to keep some global lists (queues?) of these timer objects, of these network request objects, of these documents, that are currently active:

    • as GC roots, to prevent them from being garbage-collected
    • as targets for events received from the OS, e.g. for the network APIs
    • as organisation units for events generated by the runtime itself, e.g. for the timer APIs

    Still these are typically managed separately by each subsystem, not in a single huge table.