js implements asynchronous loop implementation code
- 2020-12-21 17:58:16
- OfStack
The problem
You may have problems implementing asynchronous loops.
Let's try writing an asynchronous method that prints the index value of a loop once.
<script>
for(var i = 0; i < 5; i++){
setTimeout(function(){
document.writeln(i);document.writeln("<br />");
},1000);
}
</script>
The output of the above program is:
5
5
5
5
5
why
The end of each time (timeout) points to the original i, not a copy of it. So, the for loop causes i to grow to 5, after which timeout runs and calls the current value of i (i.e., 5).
The solution
There are several different ways to copy i. The most common and common approach is to create a closure by declaring a function and passing i to this function. We're using a self-calling function here.
Run the code
<script>
for(var i = 0; i < 5; i++){
(function(num){
setTimeout(function(){
document.writeln(num);document.writeln("<br />");
},1000);
})(i);
}
</script>
The output
0
1
2
3
4