for(var i=1;i<5;i){
setTimeout(function(){console.log(i)},i*1000);
}
For loop here It is completed first
Then the value of i has become 5
Then the for loop is executed first, so why is i*1000 executed
滿天的星座2017-05-18 11:02:35
When the for loop is executed, it is equivalent to writing 4 timer functions in the page. At this time, the timer function has not yet been executed, and the value of the i variable in the global is 5; when the timer time is up, the timer functions are executed in sequence. Print out 4 5's in sequence.
This example is not a closure. The closure needs to be written like this, which is equivalent to writing four immediately executed functions on the page. The actual parameters received by these four functions are 1, 2, 3, and 4 in order. According to the closure Features: When the timer ends, the timer function can access the actual parameters received by its outer function, so it will print out 1, 2, 3, 4 in sequence
for(var i=1;i<5;i++){
(function(i){
setTimeout(function(){console.log(i)},i*1000);
})(i)
}
给我你的怀抱2017-05-18 11:02:35
In the computer, any variable must open up a space in the memory to store, and then they all have an address. If you have studied C language or assembly language, you should know this better.
Let’s first talk about why i outputs 5 every time. Because i's space (that is, the memory space used to store i, scientifically called "stack") has been modified five times, and when the anonymous function is executed, i's space stores 5.
Let’s explain why the second parameter is different every time. i*1000
并没有修改i
的值,而是会产生一个结果。那么这个结果必然要找地方去存。存储在哪呢?setTimeout
每被调用一次,都会开辟一段内存空间,其中一部分空间就用于存储它的两个参数。其中一个参数就是刚才i*1000
产生的结果。而setTimeout
被调用了5次,于是存储了5个结果!没错,是在5个不同的空间存储了5个结果,而不是像i
The same space has been modified 5 times! As you can imagine, this approach is very memory intensive.
Can you understand this explanation?
phpcn_u15822017-05-18 11:02:35
When the for function enters the main thread, each setTimeout enters the task queue to wait in turn. After the for is executed, the setTimeout in the task queue enters the main thread for execution. Without a closure, i is already 5 when setTimeout is executed; with a closure, the value of i will be saved when setTimeout enters the task queue.
See: Event Loop