3 ms·
In my time I have encountered quite a few descriptions of how the event loop works in JavaScript. What I would like to find is _why_ do they work like this. W
by Lerc 9y ago
In my time I have encountered quite a few descriptions of how the event loop works in JavaScript.
What I would like to find is _why_ do they work like this. What is so important that this is the way it must be done. We live with browsers that lock up for a while until they figure out that some code has inadvertantly done a while(true). Promises and similar callback amelioration techniques took ages to turn up, when without the event model they might never have been required at all. Is there a reason for this? Is it a good reason?
- pavlov 9y agoThe reason is that JavaScript runs within the same event loop as the browser GUI itself. The history of JavaScript is that it started as a sort of "quick and dirty" scripting language at Netscape. Creating a completely separate event model wasn't possible in those circumstances, so JavaScript ended up being shaped by the single-threaded lowest common denominator of Win32 and other platforms that Netscape ran on.
- skybrian 9y agoThe tradeoff is that JavaScript programmers don't have to understand concurrency or deal with locking. Threads in Java (which became popular around the same time) are trickier both to implement and to use. Early multithreading was buggy, even at the OS level. You also don't gain a lot from multithreading in typical UI event handling. Most event handlers have to finish quickly anyway or the user will notice lag in updating the display. A UI that responds to events slowly and out of order would confuse users, even if it had no concurrency bugs (which is unlikely).
- jayflux 9y agoBecause it's a great (quick and easy) way of making sure JavaScript and the browser's internal rendering functions don't run at the same time and cause data races. Asynchronous callbacks share the same queue as gui tasks, and those tasks can run whilst JS is waiting on an action or an I/O task to finish. As the UI uses the same thread as JS, if JS blocks, this would lock up the whole window (clicking on things would do nothing), so it's important functions don't take too long or suspend the thread. There was an experiment within servo to see if rendering and JS could run in separate threads entirely, but I'm not sure how that went? https://github.com/servo/servo/wiki/Design https://github.com/servo/servo/wiki/Design