Question
You may run into problems when implementing an asynchronous loop.
Let’s try to write an asynchronous method that prints the index value of the loop once in a loop.
<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
Reason
Every timeout (timeout) points to the original i, not its copy. So, the for loop increments i to 5, then timeout runs and calls the current value of i (which is 5).
Solution
There are several different ways to copy i. The most common and commonly used method is to create a closure by declaring a function and passing i to this function. We use 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>
Output
0
1
2
3
4