JavaScript asynchronous mechanism

Source: Internet
Author: User

JavaScript asynchronous mechanism
JavaScript is executed asynchronously in a single thread. A single thread means that the Code will be executed one by one in the task queue in sequence. Asynchronous representation of the order of JavaScript code in the task queue is not exactly the same as the order of code writing. For example, the time when tasks such as event binding, Ajax, and setTimeout () occur is "unpredictable. Since JavaScript is a single-threaded mechanism, why is Ajax asynchronous? How is setTimeout () executed? In a browser, the JavaScript engine is executed in a single thread. That is to say, at the same time, only one piece of code can be executed by the JavaScript engine. When a page is loaded, the JavaScript engine will sequentially execute all JavaScript code on the page and execute the synchronization code first. Asynchronous code is added to the task queue of the JavaScript engine by the event trigger engine in the order of "event occurrence". After all the synchronous code is executed, the JavaScript Engine executes asynchronous code in the order in the task queue. The following is an answer from zhihu: the JavaScript engine runs in a single thread. the browser only has one thread at any time to run JavaScript programs. The browser kernel is multi-threaded, and they work together under the Internal Control to maintain synchronization. A browser must implement at least three resident threads: JavaScript Engine threads, GUI rendering threads, and browser event triggering threads. The JavaScript engine is based on the event-driven single-thread execution. The JavaScript Engine waits for the arrival of tasks in the task queue and then processes them, the browser has only one JavaScript thread running JavaScript programs at any time. The GUI rendering thread is responsible for rendering the browser interface. When the interface needs to be repainted or Reflow is triggered due to some operation, this thread will execute. However, you must note that the GUI rendering thread and the JavaScript engine are mutually exclusive. When the JavaScript engine is executed, the GUI thread will be suspended, the GUI update is immediately executed when the JavaScript engine is idle in a queue. Event trigger thread. When an event is triggered, the thread adds the event to the end of the queue to be processed, waiting for processing by the JavaScript engine. These events can come from the code blocks currently executed by the JavaScript engine, such as setTimeout, other threads from the browser kernel, such as mouse clicks and Ajax asynchronous requests, however, because of the JavaScript single-threaded relationship, all these events have to be queued for processing by the JavaScript engine (asynchronous code is executed only when no synchronous code is executed in the thread ). After learning about the asynchronous execution mechanism of a single JavaScript thread, let's take a look at the specific situation of setTimeout () and setInterval () during execution. When the setTimeout () and setInterval () setTimeout () JavaScript Engines execute setTimeout (fn, 10), on the one hand, they continue to execute the synchronization code after setTimeout (fn, 10, at the same time, start timing and insert fn into the task queue after 10 ms. After all the synchronous code is executed (the JavaScript engine is idle), the asynchronous code in the task queue is sequentially executed. Therefore, setTimeout (fn, 10) cannot be accurately executed after 10 ms, but is greater than or equal to 10 ms. The following two pieces of code give you a more intuitive impression on the execution sequence of setTimeout. Section 1: console. log (1) setTimeout (function () {console. log ('A')}, 10); setTimeout (function () {console. log ('B')}, 0); var sum = 0; for (var I = 0; I <1000000; I ++) {sum + = I;} console. log (sum); setTimeout (function () {console. log ('C') ;}, 0); output result: the execution logic of promises-1 code, which vertically represents the time, and the execution sequence of the synchronized code on the left, the right side indicates the task queue of the asynchronous code, and the arrow from left to back indicates that the asynchronous code is inserted into the task queue. The second segment of promises-3 removes a 0: console from the upper limit of the for loop. log (1) setTimeout (function () {console. log ('A')}, 10); setTimeout (function () {console. log ('B')}, 0); var sum = 0; for (var I = 0; I <100000; I ++) {sum + = I;} console. log (sum); setTimeout (function () {console. log ('C') ;}, 0); output: The difference between promises-2 and the for loop execution time is different, the for loop execution time of the first code is more than 10 ms, so the console. log ('A') is first inserted into the task queue. After the for loop is executed, the console. log ('C') is inserted into the task queue. The for loop execution time of the second code is less than 10 ms, so console. log ('C') is first inserted into the task queue. The execution method of promises-4 setInterval () is different from that of setTimeout. If setInterval (fn, 10) is executed, the timer event is triggered every 10 ms. Same as setTimeout (), if no synchronization code is currently being executed (the JavaScript engine is idle), the fn method corresponding to the timer will be executed immediately. Otherwise, fn will be added to the task queue. Because the timer event is triggered every 10 ms, it is possible that the last event processing method fn has not yet been executed and is still waiting in the queue when an event is triggered, at this time, the new timer event is discarded and the next timer starts. Note that the actual execution interval of fn two times may be less than the set interval because of the JavaScript engine's single-thread asynchronous execution method. For example, after the processing method of the previous timer event is triggered, it takes 5 ms to get the chance of execution. The second timer event will be executed immediately after the processing method is triggered. The interval between the two is actually only 5 ms. Therefore, setInterval () is not suitable for precise scheduling at fixed intervals. The following code illustrates the problem: console. log (1) var interval = setInterval (function () {var date = new Date (); console. log (date. getMinutes () + ':' + date. getSeconds () + ':' + date. getMilliseconds () ;}, 10); var sum = 0; for (var I = 0; I <1000000; I ++) {sum + = I;} console. log (2); // clear the timer to avoid freezing the browser setTimeout (function () {clearInterval (interval) ;}, 100); the output result is: promises-5, the interval between the first two setInterval () operations is only 4 ms. Because after setInterval () is triggered for the first time, the method in it is not executed immediately, but is executed only after the synchronization code is executed. This process takes 6 ms. Therefore, when the first method is executed 4 ms later, the second method is also executed. Starting from the second setInterval () trigger, the subsequent executions are not blocked, so the interval is around 11 ms. In general, both setTimeout () and setInterval () cannot meet the precise time interval. If the set interval is 10 ms, the interval between fn execution in setTimeout (fn, 10) may be greater than 10 ms, while setInterval (fn, 10) the interval between fn execution in may be less than 10 ms.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.