In the work, you need to write a latency pop-up window and think of setTimeout in for. The result shows that there is no latency as required.
So I wrote a simple test:
For (var k = 1; k <= 9; k ++ ){
SetTimeout (aa (k), 1000 );
Console. log (k );
}
Function aa (k ){
Console. log ('K: '+ k );
}
It was found that there was no waiting at all. On the Internet, it was said that setTimeout was asynchronous. That is to say, the for operation is complete and the setTimeout operation is still in progress. However, this shows that the method in setTimeout is executed, but there is no latency.
Change to setTimeout (aa (k), 1000 * k); this problem still exists.
1. Use setInterval () to simulate:
Var d = 1;
Var timer = setInterval (function (){
Console. log (d );
D ++;
If (d> 9) clearInterval (timer );
},1000 );
2. Closure implementation:
For (var j = 1; j <= 9; j ++ ){
(Function (j ){
SetTimeout (function timer (){
Console. log (j );
}, 1000 * j );
}) (J );
}
3. Define block variables for implementation:
For (let I = 1; I <= 9; I ++ ){
SetTimeout (function timer (){
Console. log (I );
}, 1000 * I );
}
For the next reference.