Code:
1 varVal1=0;2 varVal2=0;3 varVal3=0;4 5 for(vari1=1;i1<=3;i1++){6 varI2=I1;7(function(){8 vari3=I2;9SetTimeout (function(){Tenval1+=I1; Oneval2+=I2; Aval3+=i3; -},1); - })(); the } - -SetTimeout (function(){ - Console.log (val1); + Console.log (val2); - Console.log (VAL3); +},100)
Question: Please write out the results of the code printed in this section.
Correct answer: 12,9,6
Parsing: Functions in settimeout Run after the code has run, because JavaScript is a single-process, event-looping mode, and settimeout is adding functions to the time loop queue after a set time. After joining the queue, you also need to wait for the currently executing function synchronization code to complete before you can perform functions that are joined to the queue by settimeout. Then look at I1,i2,i3, because Var is a function-level scope, so i3 in every anonymous function is redefined, its scope is only in the current anonymous function, so the last settimeout function used in the i3 is 1, 2, 3,i2 and I1 are located in the global scope, The difference is that i1 last more than I2, so the final value of I1 is 4,i2 the last value is 3. So val1=3*i1=12,val2=2*i2=9.
JavaScript Learning Note: Closure (4)