Using a self executing anonymous function to solve the problem of a for loop using a closure _javascript tips

Source: Internet
Author: User
Tags anonymous closure

This code outputs 10 10 instead of the expected 0 to 9, because the closure is a reference to I, and then the function executes I has become 10

Function F1 () {
for (var i = 0; i < i++) {
settimeout (function () {
alert (i); 
}, 1000);
}
F1 ();

To solve the above problem, you can use the anonymous function of self execution

function F2 () {for
(var i = 0; i < i++) {
(function (e) {
settimeout (function () {
alert (e); 
}, 1000);
} (i);
}
F2 ();

The anonymous function here takes I as an argument, where E will have a copy of I, and the reference is a reference to E, which avoids the problem

Related Article

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.