Why the immediate execution function can skip the event queue and execute immediately

rookie problem, ask for a favor

for (var I = 0; I < 5; iPP) {
setTimeout (function () {console.log (I);}, I * 1000);
}

know that the output of five 5s knows that this fast is caused by the event queue and scope, but the results are different when using closures;

for (var I = 0; I < 5; iPP) {

(function(x) {
    setTimeout(function() { console.log(x); }, x * 1000 );
})(i);

}

output 0, 1, br 2, 3, 4 at a time; < 1 > but what is the effect of this and executing the function immediately? Did you directly change the event queue?

ask for advice from the big god, boss ~


the front-end vegetable chicken expresses its own views:

"";

i,xi

5 is a loop in which each iteration captures an I for itself at run time. The following code creates a scope by declaring a function and executing it immediately. Take a look at my article closure

.
Menu