Event loop--Single thread principle

Source: Internet
Author: User

Http://www.haorooms.com/post/js_xiancheng

https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

Task Queue
    • Main thread: Executing code that generates the function call stack.
    • MACRO-TASK (macro task, new name: Task) includes: script (whole code), SetTimeout, SetInterval, setimmediate, I/O, UI rendering.
    • Micro-task (micro task, new name: Jobs) includes: Process.nexttick, Promise, Object.observe (deprecated), Mutationobserver (HTML5 new feature, only one in queue)
Task category
    • Synchronous task, the statement executes only in the order of the statement, the preceding statement is not executed until the previous execution is completed.
    • Asynchronous task, the statement is not executed in the order of the statement, when executed to the code, added to the corresponding task queue, deferred execution.
Single Thread

The main thread starts the first loop from script (the whole code). The global context then enters the function call stack. Until the call stack is emptied (global only), then all jobs are executed. After all the executable jobs have been executed. The loop starts again from the task, finds one of the task queues executes, and then executes all of the jobs, so it's going to loop.

Precautions
    • SetTimeout minimum interval cannot be less than 4 milliseconds, otherwise it will automatically increase.
    • DOM rendering is performed every 16 milliseconds because the display is refreshed once hz,16ms.
    • The Process.nexttick task maintains a single queue in jobs and executes before other jobs tasks.
    • The bubbling event is inserted in the main thread directly after the child element event execution is complete. If the main thread is not empty, it will take precedence over the jobs execution.
Classic example

Example: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

Click with mouse
<div class="outer">  <div class="inner"></div></div>// Let's get hold of those elementsvar outer = document.querySelector('.outer');var inner = document.querySelector('.inner');// Let's listen for attribute changes on the// outer elementnew MutationObserver(function() {  console.log('mutate');}).observe(outer, {  attributes: true});// Here's a click listener…function onClick() {  console.log('click');  setTimeout(function() {    console.log('timeout');  }, 0);  Promise.resolve().then(function() {    console.log('promise');  });  outer.setAttribute('data-random', Math.random());}// …which we'll attach to both elementsinner.addEventListener('click', onClick);outer.addEventListener('click', onClick);// 输出结果clickmutateclickmutatepromisepromisetimeouttimeout
Advanced--Through JS execution
  <div class= "outer" > <div class= "inner" ></div></div>//let's get hold of those Elementsvar outer = document.queryselector ('. Outer '); var inner = document.queryselector ('. inner ');//Let's listen for Attribute changes on the//outer elementnew mutationobserver (function () {Console.log (' mutate ');}).  Observe (outer, {attributes:true});//Here's a click Listener...function onClick () {console.log (' click ');  SetTimeout (function () {console.log (' timeout ');  }, 0);  Promise.resolve (). Then (function () {console.log (' Promise ');  }); Outer.setattribute (' Data-random ', Math.random ());} ... which we ' ll attach to both Elementsinner.addeventlistener (' click ', OnClick); Outer.addeventlistener (' Click ', OnClick); Inner.click ();//output result clickclickmutatepromisepromisetimeouttimeout  

Because the Click event is JS execution, Inner's OnClick function completes, the scope of the Inner.click () statement has not been rolled back, the main thread call stack is not empty, resulting in the jobs queue task will not be executed, mutate and promise statements are not in the event loop Executed to. The OnClick function of the outer is thus executed. After the outer's OnClick function is executed, the Inner.click () statement goes back to the stack and executes the jobs task.

Only one mutate is due to the jobs queue, there can only be one mutationobserver task, and the second time when it is created, the previous Mutationobserver task is not executed and GU is no longer created.

Event loop--Single thread principle

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.