JS implement asynchronous loop implement code _javascript skill

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.