Part III. Time6 min · en inglés

09

The Event Loop

JavaScript in the browser always had one thread, and nobody intended to give it a second. A page lived like this: the browser waited for something to happen, and when something did, say the user clicked a button or a response came from the server, it called the right function and waited for it to finish. While the function ran, nothing else happened on the page. Then the browser took the next event from the queue, and so on round and round. That loop is what is called the event loop. The language itself knows nothing about it: as the first chapter said, the loop is described in the HTML standard, and Node has its own.

The design is primitive, but it has a great virtue. Since nobody interrupts a function once it has started, nobody can change shared data in the middle of its work. To a Java or C++ programmer this will seem a miracle. There, two threads incrementing the same counter at once can lose half the increments, so shared data is guarded by locks, and locks have their own troubles: deadlocks, where two threads wait for each other forever, and bugs that show up once a month on a loaded server and never on the developer’s machine. In JavaScript this whole class of bugs does not exist within one piece of code, because only one piece runs at a time.

The drawback is just as clear. If a function computes for a long time, the page freezes. The older generation remembers the «A script on this page is not responding» dialog, which the browser showed when some script held the loop for too long, asking whether to kill it.

Gratis, solo falta un paso

El resto del libro es gratis

Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.

¿Tienes cuenta INITE? Entra y el libro se abre sin correo.

No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.

Cómo se guarda la dirección