Home > Web Front-end > JS Tutorial > body text

Use self-executing anonymous functions to solve the problem of using closures in for loops_javascript skills

WBOY
Release: 2016-05-16 16:36:28
Original
1297 people have browsed it

This code outputs 10 10s instead of the expected 0 to 9, because the closure contains a reference to i, and then i has become 10 when the function is executed

function f1(){
for(var i = 0; i < 10; i++) {
setTimeout(function() {
alert(i); 
}, 1000);
}
}
f1();
Copy after login

To solve the above problems, you can use self-executing anonymous functions

function f2(){
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
alert(e); 
}, 1000);
})(i);
}
}
f2();
Copy after login

The anonymous function here takes i as a parameter, and the e here will have a copy of i, and the reference is a reference to e, which avoids the above problem

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