JavaScript synchronization, asynchronous, callback execution sequence analysis __java

Source: Internet
Author: User
Tags closure message queue

The reason why this article is written, because in the pen test, you will encounter a very classical topic, about the output of settimeout, the following we first look at a topic:

for (var i = 0; i < 5; i++) {
    settimeout (function () {
        console.log (i);
    }, 1000);
}

Console.log (i);
I believe that as long as the front-end pen test questions have seen such a topic, then the output of what is the result.

The first possible answer: 0 1 2 3 4 5 5

Second possible answer: 5 5 5 5 5 5 5 (after each 5 seconds output)

Obviously the second result is correct, and then we'll analyze the subject. First look at a password or a method that everyone is using:

Sync priority, asynchronous pull over, callback bottom

Expression by formula is: Synchronous => asynchronous => callback

Now, based on this password, let's analyze why this is the result:

1 The For loop and the external console of the loop body are synchronized, so the For loop is executed first, then the external console.log is executed. (Sync first)

2 for loop inside there is a settimeout callback, he is the bottom of the existence, can only be last executed. (Callback bottom)

So why do we have to export 5 first?

This is also very good to understand that the For loop executes first, but does not give the SetTimeout pass (callback bottom), and so the For loop executes, the settimeout is passed, and the external console prints 5 because the For loop execution completes.


So how do we get to output 0 1 2 3 4 5?

There are two kinds of methods I know at present, the first one is to use let method, the second is to use closure method.

1, using Let

for (Let i = 0; i < 5; ++i) {
    settimeout (function () {
        console.log (i);
    }, 1000);
}
The output at this point is:

0
1
2
3
4

But now, after one second, output 0 1 2 3 4 5, and if you want to output this result every second, you can modify the program to read as follows:

for (Let i = 0; i < 5; ++i) {
    settimeout (function () {
        console.log (i);
    }, i*1000);
}
2, closure of the method

for (var i = 1; I <=20; i++) {
    (function (i) {
        settimeout (function timer () {
            console.log (i);
        }, i*1000) c4/>}) (i);
}
As a result, this can be explained using the knowledge of closures, or it can be used to assist in understanding the scope.

because var i = xxx is a function-level scope, the variable i is passed through an immediate function to include it in the scope of this function. In each loop, this immediate function saves the incoming I value, so its cyclic expansion results are:

(function () {
    var count = 0;
    settimeout (function timer () {
        console.log (count);
    }, Count * 1000);
}) ()
(function () {
    var count = 1;
    settimeout (function timer () {
        console.log (count);
    }, Count * 1000);
}) ()
(function () {
    var count = 2;
    settimeout (function timer () {
        console.log (count);
    }, Count * 1000);
}) ()
(function () {
    var count = 3;
    settimeout (function timer () {
        console.log (count);
    }, Count * 1000);
}) ()
(function () {
    var count = 4;
    settimeout (function timer () {
        console.log (count);
    }, Count * 1000);
}) ()
(function () {
    var count = 5;
    settimeout (function timer () {
        console.log (count);
    }, Count * 1000);
}) ()

This is mainly about the order of synchronization and callback execution, and then I'll give you an example of synchronization, Asynchrony, and callbacks.
Let A = new Promise (
  function (resolve, reject) {
    Console.log (1)
    settimeout (() => Console.log (2), 0)
    Console.log (3)
    Console.log (4)
    Resolve (True)
  }
)
A.then (v => {
  Console.log (8)
}) Let

B = new Promise (
  function () {
    console.log (5)
    settimeout (() => Console.log (6), 0)
  }
)

Console.log (7)

Before I look at the correct results, I first analyze the topic (Synchronous => Asynchronous => callback): 1 To see the synchronization code: A variable is a promise, at the beginning everyone would think that promise is not asynchronous. No, in fact, promise is asynchronous, refers to his then () and catch () method, promise itself is still synchronized, so here is the first implementation of a variable internal promise synchronization code. (Sync first)
Console.log (1)
SetTimeout (() => Console.log (2), 0)/callback
Console.log (3)
Console.log (4)
2 Promise has 4 console, the second is a settimeout callback (callback bottom, so temporarily do not output). So here we first output the 1,3,4, and the callback method is dropped into the message queue.
3) then executes resolve (true), enters the then (), then is asynchronous, below also has the synchronization not to execute, therefore then also goes to the message queue to wait. (Asynchronous pull over)

4 b variable is also a promise, and a, the same is synchronized, the implementation of internal synchronization code, output 5,settimeout is callback, to the message queue waiting, here output 5.
5 The bottom sync output 7.
6 Now that the synchronized code is finished, JavaScript runs to the message queue to call the asynchronous code: asynchronous, out of the execution. There is only one asynchronous then, so output is 8.
7 at this time, asynchronous also over, turn to callback function: callback, out of execution. There are 2 callbacks in the queue and their time is set to 0, so they are not affected by time, only in the order of queuing. Then output the callback 2 in a, and then the callback 6 in B.
8 The final output result is: 1, 3, 4, 5, 7, 8, 2, 6.

Here, explain the end. On the implementation of the order or more to practice and understanding, JavaScript profound, not a word can be summed up.


Related Article

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.