On the problem of block-level scope and closure

first of all, these two pieces of code

1:
 function createFunctions() {
    var result = new Array();
    for (var i = 0; i < 10; iPP) {
        result[i] = function() {
            return i;
        };
    }
    return result;
}
var funcs = createFunctions();

for (var i = 0; i < 10; iPP) {
    alert(funcs[i]());
}
2:
for (var i = 0; i < aLi.length; iPP) {
    aLi[i].onmouseover = function() {
        this.style.background = "red";
    };
    aLi[i].onmouseout = function() {
        this.style.background = "-sharpfff";
    }
}

excuse me:
1. Why is it that in Code 1, the contents of the function are not executed until the final I becomes 10, while Code 2 is executed every time in the order in which I is incremented?
2. Does this have anything to do with the asynchronous execution of js? But I also feel very confused about the order of execution here. I can"t figure it out clearly. Please tell me in detail

.
Mar.09,2021

In

code 1, all the functions in the array result refer to variables in createFunctions, and after the for loop ends, I has a value of 10, so all you print out is 10.

this is actually a problem of closure delay calculation:

result[i] = function() {
            return i;
};  //   i  `result[i]`  i  10 

result[i] = function() {
            return i;
        };
    }

the I variable in return I in this code is the free variable , whose value is determined by parent scope when is created . When the function is executed, the parent scope I is already 10, so the output is 10

.

understand free variables, scope and execution environment

Menu