tryurbest tryurbest - 15 days ago 5
Javascript Question

setInterval - How to preserve passed in variable

I did some digging around on SO and could not find exactly what I am trying to achieve.

In simplistic terms I have a function like

function(){
for(i=0;i<10;i++){
setInterval(function(){ alert(i);), 1000)
}
}


What I would expect is 10 setIntervals that would alert 1 to 10 every 1 second, what happens is it would alert 10 always since 'i' is 10 at the end of for loop. How do I pass 'i' to setInterval anonymous function so that I can preserve the value of i in setInterval?

Above was a simplistic version of my actual problem. I am actually trying to do this
var timers = [];

function(obj){
//Clear any intervals
for(i=0;i<timer.length;i++){
clearInterval(timers[i]);
}

// Empty timers Array
timers = [];

for(i in obj){
//My object from the dom. This guy is what I am trying to preserve
my_obj = document.getElementById(i);
if(obj[i] === "Something"){
timers.push(setInterval(function(){
my_obj.replace_class(["Something", "Otherthing"],"Something");
}, 1000)
}
}
}


my_obj in the above code always refers to id = last 'i' in obj.

Do I make sense?

Answer

This should do the trick ;)

for(i = 1; i < 11; i++){
  (function(local_i){ 
    setInterval(function(){ console.log(local_i); }, 1000 * local_i)
  })(i);
}