how to keep the value of a variable in a closure

Posted by Florian Fida on Stack Overflow See other posts from Stack Overflow or by Florian Fida
Published on 2011-01-09T15:21:20Z Indexed on 2011/01/09 15:53 UTC
Read the original article Hit count: 170

Filed under:
|
|

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, comments or tips!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures