Listening to events in JS

Viewed 79

I have heard a lot about how JS is single threaded and asynchronous, and I know about the event loop, and the callback queue.

What I don't understand is how can a single threaded language be listening to events and adding event handlers to the queue while it executes other code?

For example clicking a button while a long loop is running will add its callback to the queue even though the thread is occupied.

Thank You

2 Answers

The answer is that the OS (or Javascript, for code-generated events) sends events to the JS in the browser, and these events are put on a queue for for processing. Javascript's one thread takes events off the queue and processes them until there are none left, at which time it waits for the next event to come in. For more, read about message queues: https://en.wikipedia.org/wiki/Message_queue

Simply put, browsers are not written in javascript, and javascript is not what handles events.

UI events are first messaged to the browser by the OS, then the browser will handle these messages and queue a task to build up the DOM Event and dispatch it, where the related JavaScript callbacks may finally fire.

Only the last part involves JavaScript. You can very well have an User Agent (UA) that doesn't implement JavaScript but still does handle some UI events (e.g CSS pointer-events, HTML inputs, media controls etc.)

How this is handled will depend on the UA.

For very long, in the exact example you gave, browsers were unable to handle the clicks that were fired while the event loop was busy (IIRC latest IE still wasn't able to do so). It's only in modern browsers that they started to use multi-process architectures which are able to communicate (Inter-Process Communication) by sharing different message queues.

So even though the "main" renderer thread that does execute the various tasks of the event loop is busy, e.g executing js, other processes can still run in parallel and queue new tasks on the appropriate task queue.
When the renderer thread is done with its long task, a new task has been queued and it can process it.

Related