Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep the value of a variable in a closure

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!

like image 221
Florian Fida Avatar asked Feb 26 '23 10:02

Florian Fida


1 Answers

Just create a function and call it.

while (i--) {
    (function(i) {
        // use i here
    })(i);
}
like image 53
Nikita Rybak Avatar answered Feb 28 '23 10:02

Nikita Rybak