javascript - A setTimeout problem
某草草
某草草 2017-06-14 10:53:57
0
3
572

function test() {

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

想问一下,为什么最后会弹出5?
某草草
某草草

reply all(3)
仅有的幸福

First of all, it is recommended that the subject read an article about JavaScript
Detailed explanation of JavaScript Event Loop operating mechanism

This article explains in detail the principle of JavaScript event polling

Let’s talk about the topic’s question:

1. The main thread will execute first. When test() is executed, two setTimeouts will be put into the task queue at the same time, and then alert(0) will be executed, so 0 will be output first. At this time, the value of a is 19, because setTimeout It has not been executed yet, there is no other assignment opportunity for a;

2. After the main thread is executed, it then polls the task queue to execute the scheduled task. Since the first setTimeout time is shorter than the second one, the first setTimeout callback is executed first. At this time, alert(a) will be output after about 1s. One step of 19, then a is assigned a value of 5;

3. Then execute the second setTimeout. Because both setTimeouts are put into the queue at the same time, the callback of the second setTimeout will be executed about 2s later. At this time, the 5 obtained in the previous step will be output, and then a will be Assigned value is 4. The reason why it is about 2s is because the Javascript timer is not accurate

三叔

You will have a more thorough understanding of the mechanism through your own debug

漂亮男人

After the first timer is executed, the global a has become 5
The change of a in the test function: 1-19-5-the last alert(a)-4

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template