Home >Web Front-end >JS Tutorial >js implements asynchronous loop implementation code_javascript skills

js implements asynchronous loop implementation code_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:15:271360browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn