admin管理员组文章数量:1401939
i need to create multiple javascript functions which have a static id inside, so the function itself knows what data to process.
Here is some code:
(function(){
function log(s){
if(console && console.log) console.log(s);
else alert(s);
}
var i = 10; while (i--){
window.setTimeout(function(){
// i need i to be 10, 9, 8... here not -1
log(i);
},500);
}
})();
The problem ist that i allways gets updated by the loop, and i need to prevent this.
Thanks in advance for any help, ments or tips!
i need to create multiple javascript functions which have a static id inside, so the function itself knows what data to process.
Here is some code:
(function(){
function log(s){
if(console && console.log) console.log(s);
else alert(s);
}
var i = 10; while (i--){
window.setTimeout(function(){
// i need i to be 10, 9, 8... here not -1
log(i);
},500);
}
})();
The problem ist that i allways gets updated by the loop, and i need to prevent this.
Thanks in advance for any help, ments or tips!
Share Improve this question asked Jan 9, 2011 at 15:21 Florian FFlorian F 4,3633 gold badges32 silver badges34 bronze badges3 Answers
Reset to default 3Just create a function and call it.
while (i--) {
(function(i) {
// use i here
})(i);
}
(function(){
function log(s){
if(console && console.log) console.log(s);
else alert(s);
}
var i = 10; while (i--){
(function() { // start anon func
var copy = i; // copy loop variable
window.setTimeout(function(){
log(copy); // refer to copy
},500);
})(); // end anon func and call it immediately
}
})();
A little better approach to using an immediately invoked function in each iteration, is to have your log()
function return a function.
(function(){
function log(s){
return function() {
if(console && console.log) console.log(s);
else alert(s);
};
}
var i = 10; while (i--){
window.setTimeout( log( i ),500 );
}
})();
The overall result is that you end up constructing fewer function objects.
If you wanted the calls to be at an interval, either use setInterval()
, or change this:
window.setTimeout( log( i ), 500 );
to this:
window.setTimeout( log( i ), i * 500 );
本文标签: javascripthow to keep the value of a variable in a closureStack Overflow
版权声明:本文标题:javascript - how to keep the value of a variable in a closure - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744244915a2596963.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论