Again to brush face questions, haha.
Requirements: Use for loop to print 1-10, each number appears at an interval of about 500ms.
Analysis: Research points-closures, block-level scopes
Mode one, the use of closures + immediately execute the function, his thoughts at that time also think so, but the results do not reflect the interval 500ms
for (var i = 1; i <=; i++) { setTimeout (function (i) { console.log (i); }) (i), (a); }
After modification, the result satisfies the requirement: 1.setTimeout each time interval 500*i, guaranteed every 500ms output 2. Move immediate execution to the outer layer
/** * Using a For loop to print 1-10, each number appears at an interval of approximately 500ms * method one, using closures, note settimeout, every 500ms, so the interval between each pass is multiplied by I */for (var i=1;i<=10;i++) { (function (i) { setTimeout (function () { console.log (i); },500*i); }) (i);}
Method two, using Let,let itself is a block-level scope
for (let i=1;i<=10;i++) { setTimeout (function () { console.log (i); },500*i);}
JS face test--use for loop to print 1-10, each number appears at the interval of about 500MS