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

本文标签: javascripthow to keep the value of a variable in a closureStack Overflow