JavaScript depth of the operating mechanism

JavaScript depth of the operating mechanism

1. Basics

  • JavaScript is a single threaded language, proposed Web-Worker in the latest in HTML5, JavaScript is single threaded but the core remains unchanged.

  • Js as browser scripting language, its main purpose is to interact with the user, and DOM operation, therefore Js is single-threaded, but also to avoid the simultaneous operation of a contradiction with the DOM;

  • To take advantage of the computing power of multi-core CPU, H5 of Web Worker achieve "multi-threaded" actually refers to "multiple child threads", fully controlled by the main thread, and does not allow the operation DOM;

  • All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack);

  • If, during the implementation of micro-micro-task job queue by adding a new micro-task, the task will join the new micro end of the queue, and then will be executed;

Asynchronous operation 2.Js

  • setTimeOut
  • setInterval
  • ajax
  • promise
  • I / O

3. synchronous or asynchronous tasks Tasks

  • Synchronization tasks (synchronous): queued for execution on the main thread task, only the first task is finished, you can perform a task after;
  • Asynchronous tasks (asynchronous): do not enter the main thread, and enter the task "Task Queue" (task queue), only the "Task Queue" notify the main thread, an asynchronous tasks can be carried out, the task will enter the main thread.

4. The micro-macro task or tasks

In addition to generalized synchronous and asynchronous tasks task, we have a finer definition of the mission:

  • Macro task (macro-task): Code whole script, setTimeOut, setInterval
  • 微任务(mincro-task):promise.then、promise.nextTick(node)

5.JavaScript event loop

Here Insert Picture Description

Content maps to express in words to express the words:

  • Synchronous and asynchronous tasks, respectively, into a different implementation of "place" into the main thread synchronization, asynchronous enter the Event Table and registration functions.
  • When the specified things done, Event Table This function will be moved into the Event Queue.
  • Task execution in the main thread is completed is empty, go to Event Queue reads the corresponding function, enter the main thread.
  • Js process exists engine monitoring process will continually checks the main thread execution stack is empty, once empty, they will go there to check for Event Queue waiting function is called. The above process is a continuous cycle, so the entire operation of this mechanism is also known as Event Loop (event loop)

6. setTimeout

  • setTimeout(() => {
        task();
    },3000)
    console.log('执行console');
    

    setTimeoutIs asynchronous, the above code to perform console.logthis task synchronization, and then perform the task ().

  • setTimeout(() => {
        task()
    },3000)
    
    sleep(10000000)
    

    The above code execution task()time required far more than three seconds, three seconds delay that good, why now it takes so long ah?

    Let's start with how the above code is executed:

    1. task()Into the Event Table and registration, timing begins.
    2. Execution sleepfunction is very slow, very slow, timing continues.
    3. 3 seconds is up, timed event timeoutis complete, task()enter the Event Queue, but sleepalso slow it, has not been performed, we had to wait.
    4. sleepFinally finished execution, task()finally entered the main thread of execution from the Event Queue.

    setTimeoutThis function is after a specified time, the tasks to be performed (in this example task()) ** was added to the Event Queue. ** Also, because of a single-threaded task to an executive, if the time required for the task ahead for too long, you can only wait, the real cause of the delay time is much greater than 3 seconds.

    We also often encounter setTimeout(fn,0)such a code, after 0 seconds to perform and what does it mean? Is not it can be executed immediately?

    The answer is no, setTimeout(fn,0)meaning that the main thread to specify a task in the first available idle time to perform, meaning how many seconds do not wait any longer, as long as synchronization tasks in the main thread execution stack full implementation is complete, the stack is empty immediately executed.

7. setInterval

  • For the execution order, the setIntervalfunction specified time intervals registered into the Event Queue, if the previous task takes too much time, we also need to wait.

  • Note that, for setInterval(fn,ms)it, we already know that not every few msseconds will be executed once fn, but every few msseconds, will fnenter the Event Queue. Once the callback function fn setInterval execution time exceeds the delay time ms, then it does not look like there is a time interval .

8. Promise与process.nextTick(callback)

  • new Promise will enter into the main thread executed immediately, while promise.then belong to micro-tasks.

  • process.nextTick(callback)Node.js similar version of the "setTimeout", a cycle call callback callback function in the event loop.

9. The order of the event loop

Loop sequence of events, decided to implement the order of Js code. After entering the code as a whole (macro task), start the first cycle. Then perform all of the micro-tasks. Then start again from the macro task, find one of the task queue is finished, and then perform all of the micro-tasks.

  • Relations event loop, macro tasks, micro-task as shown:

Here Insert Picture Description

  • Example 1 :

    setTimeout(function() {
        console.log('setTimeout');
    })
    
    new Promise(function(resolve) {
        console.log('promise');
    }).then(function() {
        console.log('then');
    })
    
    console.log('console');
    
    1. This code as a macro task to enter the main thread.
    2. First encounter setTimeout, then after it is distributed to the callback function registered macro task Event Queue. (With the same registration process is not described below)
    3. The next encounter Promise, new Promiseimmediate implementation, thenthe function to distribute micro-task Event Queue.
    4. Encountered console.log(), execution immediately.
    5. Well, the code script as the first overall macro task execution ends to see what micro-tasks? We found thenin the micro-task Event Queue inside, execution.
    6. ok, the first round of the event cycle is over, we start the second round of the cycle, of course, from the beginning of the macro task Event Queue. We found the macro task Event Queue in setTimeoutthe corresponding callback function is executed immediately.
    7. End.
  • Example 2 :

    console.log('1');
    
    setTimeout(function() {
        console.log('2');
        process.nextTick(function() {
            console.log('3');
        })
        new Promise(function(resolve) {
            console.log('4');
            resolve();
        }).then(function() {
            console.log('5')
        })
    })
    process.nextTick(function() {
        console.log('6');
    })
    new Promise(function(resolve) {
        console.log('7');
        resolve();
    }).then(function() {
        console.log('8')
    })
    
    setTimeout(function() {
        console.log('9');
        process.nextTick(function() {
            console.log('10');
        })
        new Promise(function(resolve) {
            console.log('11');
            resolve();
        }).then(function() {
            console.log('12')
        })
    })
    

    The first round of the event loop process as follows :

    1. The whole script as the first task of the macro enter the main thread encountered console.log, output 1.
    2. Encounter setTimeout, which the callback function is distributed to the macro task in the Event Queue. Let us remember to setTimeout1.
    3. Encounter process.nextTick(), which the callback function is distributed to micro-task in Event Queue. We write process1.
    4. Encounter Promise, new Promisedirect execution, output 7. thenIt is distributed to the micro-task in Event Queue. We write then1.
    5. They met setTimeout, its callback function is distributed to the macro task Event Queue, we referred to setTimeout2.
      Here Insert Picture Description
    6. On the table is the end of the first round of the event loop macro Event Queue task each case, now has an output of 1 and 7.
    7. We found process1and then1two micro-tasks.
    8. Execution process1, output 6.
    9. Execution then1, output 8.
    10. The first round of the official end of the event loop, which is a result of the output of 1,7,6,8.

    Then the second round of the event loop from setTimeout1the macro task starts:

    1. First output 2. The next encounter process.nextTick(), the same will distribute it to the micro-task Event Queue, note is process2. new Promise4 immediate execution output, thenalso distributed to micro Event Queue task, note is then2.
      Here Insert Picture Description

    2. The second round of the event loop macro end of the mission, we found process2and then2two micro-tasks can be performed.

    3. Output 3.

    4. Output 5.

    5. The second round of the event loop ends, the output of the second round of 2,4,3,5.

    The third round of the event cycle begins:

    1. This time only setTimeout2, and execution. Direct output 9.

    2. Will be process.nextTick()distributed to the micro-task in Event Queue. Denoted process3.

    3. Direct execution new Promise, output 11.

    4. Will be thendistributed to the micro-task Event Queue, note is then3.
      Here Insert Picture Description

    5. The third round of the event loop macro task execution ends, two micro-tasks to perform process3and then3.

    6. Output 10.

    7. Output 12.

    8. The end of the third round of the event loop, the third round of output 9,11,10,12.

    Whole sections of the code, a total of three event loop full output 1,7,6,8,2,4,3,5,9,11,10,12.
    (Note that in the event node dependent libuv ambiance listening environment is not identical with the front end, the output order may be errors)

10. Finally

  • Event Loop Event Loop is a way to implement asynchronous js, but also enforcement mechanisms of js.
  • javascript implementation and operation are very different, javascript in different environments, such as node, browser, Ringo and so on, implementation is different. And refers mostly run javascript parsing engine is unified.
  • Micro and macro tasks, there are many types of tasks, such as setImmediateand so on, all have in common is executed, interested students can inform themselves about.

Reference: Link

Published 33 original articles · won praise 73 · views 2781

Guess you like

Origin blog.csdn.net/weixin_46124214/article/details/104157496