setTimeout callback function for the immediate implementation

for (var i = 0; i < 5; i++) {
  setTimeout((function(i) {
    console.log(i);
  })(i), i * 1000);
}
setTimeout () callback function is an immediate execution function , 
operating results changed code is: 0,1,2,3,4,5 print out immediately
why i immediately print out the value of it?
From understanding the literal meaning: the function is immediately executed immediately without waiting for a callback, the implementation of the code is loaded immediately

try to execute the function immediately return a function, setTimeout function is to perform this function
for (var i = 0; i < 5; i++) {
  setTimeout((function(i) {
    console.log(i);
    return function() {
        console.log('回调')
        console.log(i)
    }
  })(i), i * 1000);
}

Run Results: executing the first function is executed immediately before execution function function, each i * 1000 seconds will engage the console.log ( 'callbacks') and console.log (i)

Summary: setTimeoutThe first argument must be a need to compile code or a function method , and if a line directly into executable code, then I'm sorry, this will be executed immediately, no delay effect

Guess you like

Origin www.cnblogs.com/psxiao/p/11408330.html
Recommended