Event loop
The event loop
got its name because of how it's usually implemented, which usually resembles:
while(queue.waitForMessage()){ queue.processNextMessage(); }
queue.waitForMessage
waits synchronously for a message to arrive if there is none currently.
"Run-to-completion"
Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.
函数运行时,不能被外界修改,且不可拆分运行
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.
同时如果函数执行时间过长, 将无法做其他响应, 也就是浏览器会卡住
所以作为消息处理函数应该尽量的简洁
Adding messages
In web browsers, messages are added any time an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message--likewise with any other event.
Calling setTimeout
will add a message to the queue after the time passed as second argument. If there is no other message in the queue, the message is processed right away; however, if there are messages, the setTimeout
message will have to wait for other messages to be processed. For that reason the second argument indicates a minimum time and not a guaranteed time.
setTimeout
即使到了预定的时间,但有其他消息处理函数执行中,会一直等待, 所以说这个时间参数只是最小值, 不是精确值
Several Runtime communicating together
A web worker or a cross-origin iframe has its own stack, heap, and message queue. Two distinct runtimes can only communicate through sending messages via the postMessage
method. This method adds a message to the other runtime if the latter listens to message
events.
Never blocking
A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input.
Legacy exceptions exist like alert
or synchronous XHR, but it is considered as a good practice to avoid them. Beware, exceptions to the exception do exist (but are usually implementation bugs rather than anything else).
当然对于I/O来说并不会阻塞, 他们将会异步执行, 除非你用了个alert()
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于