Problem
when you implement asynchronous loops, you may experience problems.
Let's try to write an asynchronous method that loops through the index values one at a time.
<script> for
(var i = 0; i < 5; i++) {
settimeout (function () {
Document.writeln (i);d Ocument.writeln ("<br/>");
},1000);
}
</script>
The output of the above program is:
5
5
5
5
5
Reason
Each time end (timeout) points to the original I, not its copy. So the for loop causes I to grow to 5, then timeout runs and invokes the value of the current I (that is, 5).
Solving method
There are several different ways to copy I. The most common and common method is to declare a function to create a closure and pass I to this function. We use the Self invocation function here.
Run code
<script> for
(var i = 0; i < 5; i++) {
(function (num) {
settimeout (function () {
Document.writeln (num);d ocument.writeln ("<br/>");
},1000);
(i);
}
</script>
Output
0
1
2
3
4