for(var i=0;i<10;iPP){
setTimeout((function(i){
console.log(i);
})(i),1000*i);
}
for(var i=0;i<10;iPP){
setTimeout((function(i){
return function(){
console.log(i);
}
})(i),1000*i);
}
first of all, I know that the structure executed by these two functions is that the first one prints out 0 to 9 immediately without delay, and the second function prints out 0-9
in sequence by 1 second. I understand that first executes the function immediately, first executes the function first, and then creates a function scope to keep the variable I value as an argument in this context, and then this immediately executes the function. After execution, the anonymous function that returns an anonymous function is thrown into an asynchronous queue and loops into the next tick ten times, when the anonymous function is in the global scope and retains the execution context of the immediate execution function, so at this time the print I gets the I that is the immediate execution context. I think my understanding is that there is no problem
problem is the first example. My understanding is that printing out 0 to 9 is because the printed of the function is executed immediately, and then the function is executed immediately and returns underfined, so in theory, the asynchronous action to be performed is not thrown into the asynchronous queue at this time. There is no closure because there is no reference to the immediate execution function , but I think there are some articles. Is it also because of the closure? is there something wrong with my understanding? thank you
.