First question:
No, since the variable i increases after the last successful iteration, then the condition is checked and evaluated as false , so the loop ends.
The for statement consists of:
for ([initialExpression]; [condition]; [incrementExpression]) statement
And it is executed in the following steps:
initialExpression is evaluated at the beginning- The
condition evaluated, if it is evaluated as false , the cycle ends, if it is evaluated as true , the operator is evaluated. - Calculate the statement.
- Evaluated
incrementExpression , go to step 2.
Second question:
The function is executed asynchronously after , the cycle has ended, at this time, as you know, i contains 3 .
A common workaround for this is to use a function to store the value of a loop variable for each iteration, for example:
for (var i=0; i<=2; i++) { (function (i) { setTimeout(function(){console.log(i);}, i*1000); })(i); }
source share