javascript - how to keep the value of a variable in a closure - Stack Overflow

i need to create multiple javascript functions which have a static id inside, so the function itself kn

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 badges
Add a ment  | 

3 Answers 3

Reset to default 3

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744244916a4564879.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信