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

js implements asynchronous loop implementation code_javascript skills

WBOY
Release: 2016-05-16 15:15:27
Original
1348 people have browsed it

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>
Copy after login

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>
Copy after login

Output

0
1
2
3
4

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template