tryurbest tryurbest - 1 year ago 90
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

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 = [];

//Clear any intervals

// 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"){
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 Source

This should do the trick ;)

for(i = 1; i < 11; i++){
    setInterval(function(){ console.log(local_i); }, 1000 * local_i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download