Home  >  Article  >  Web Front-end  >  Use self-executing anonymous functions to solve the problem of using closures in for loops_javascript skills

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

WBOY
WBOYOriginal
2016-05-16 16:36:281290browse

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();

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();

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

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