On the problem of immediate execution of functions and closures

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

. The

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

.
Mar.10,2021

you use IIFE. The first parameter of setTimeout is undefined.


the first example function has been executed, and there is no closure


Hello. The result of the second function is to print out 0-9 in sequence with a delay of 1 second

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e450cc-44af6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e450cc-44af6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?