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.
Free, one step away
The rest of the book is free
Leave your email and I will send a link to confirm it. Once you click it, every chapter opens here, on this device, for a year. When a new book comes out I will write to this address; reply “stop” to any email and I will not write again.
Have an INITE account? Sign in and the book opens without an email.
I do not charge for the book. If you would like to support it, you can donate from any chapter.
How your email is stored