Js implements Asynchronous Loop implementation code and js implements asynchronous code
Problem
You may encounter problems when implementing asynchronous loops.
Let's try to write an Asynchronous Method to print the index value of one loop at a time.
<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
Cause
The end of each time (timeout) points to the original I, rather than its copy. Therefore, the for loop increases I to 5, and then timeout runs and calls the current I value (that is, 5 ).
Solution
There are several different ways to copy I. The most common and common method is to create a closure by declaring a function and pass I to this function. The self-called function is used here.
Run code
<Script> for (var I = 0; I <5; I ++) {(function (num) {setTimeout (function () {document. writeln (num); document. writeln ("<br/>"); }, 1000) ;}) (I) ;}</script>
Output
0
1
2
3
4