The execution order of the setTimerout in the native js within the function

function test () {

    var a = 1;
    setTimeout(function () {
        alert(a);
        a=3;
    },1000);
    a=2;
    setTimeout(function(){
        alert(a);
        a=4;
    },3000)
}
test()
alert(0)

 :0,2,3  -sharp-sharp-sharp 

sources of topics and their own ideas

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

Jul.06,2021

1. Execute the test function with setTimeout delay, and assign a to 2
2. Execute alert (0)
3. When the first setTimeout, is executed, an is 2, and after 2 pops up, an is assigned a value of 3
4. When the second setTimeout, is executed, an is 3. After 3 pops up, an is assigned a value of 4


in the order in which the subject executes the program:
1. Declare test function = > call test ()
2. Declare the variable a = 1 = > the first setTimeout joins the queue, 1s = > a = 2 = > the second setTimeout joins queue 3s; the
3.test function ends and executes alert (0) ;
4. At the end of the current queue execution a = 2 , the first setTimeout = > alert (2) = > a = 3 , the second setTimeout a = 3 = > alert (3) = > a = 4 after
5.3s.


first of all, settimeout belongs to the time module of the JS engine in the browser, and it is normal to execute asynchronously. As for what is asynchronous, I can simply give you a few examples: for example, the time module is an asynchronous function such as click events, and callback functions are asynchronous. These will be executed at last when they are encountered, so they will print 1 first. Because when you call the function, you have a procedure called astat2, and this will be executed first, and your timeout call is 3000 and 1000, so you will first execute 1000 print 2, and finally there will be 3. That's basically it, brother. I hope it will be helpful to you


https://ppt.baomitu.com/d/64a.

take a look at this

Menu