0

Possible Duplicate:
Javascript infamous Loop problem?

With the for loop, it does nothing. Without the for loop, it works perfect.

Without the for loop:

var refreshId = setInterval(function(){
  $("#k1").fadeTo(1000,0.01,callfunc).fadeTo(1000,1);
}, 5000);
var refreshId = setInterval(function(){
  $("#k2").fadeTo(1000,0.01,callfunc).fadeTo(1000,1);
}, 5000);

and so on...

With the for loop:

for(var i=1;i<7;i++){
  var refreshId = setInterval(function(){
    $("#k"+i).fadeTo(1000,0.01,callfunc).fadeTo(1000,1);
  }, 5000);
}

What am I doing wrong here?

Community
  • 1
  • 1
David19801
  • 11,214
  • 25
  • 84
  • 127
  • 2
    Read [Closures Inside Loops](http://bonsaiden.github.com/JavaScript-Garden/#function.closures). – pimvdb Feb 25 '12 at 12:16

1 Answers1

2

As @pimvdb pointed out you have closure (setTimeout creates one) inside loop, it won't work, you should have something like:

for(var i = 1; i < 7; i++) {
    (function(e) {
        var refreshId = setTimeout(function() {
            $("#k"+e).fadeTo(1000,0.01,callfunc).fadeTo(1000,1);
        }, 5000);
    })(i);
}

You may also want to take a look at this question for more information.

Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Maybe a typo with the parameter name not replaced? Line 4, 'i' not 'e'? – Jim Blackler Feb 25 '12 at 12:22
  • +1 @David19801: If you would like a little bit more descriptive way, you could use [this little helper function](https://gist.github.com/1908200). – pimvdb Feb 25 '12 at 12:23
  • At the time I made that comment, the parameter was called 'e' but line four referenced 'i'.. pimvdb has since made the edit I had in mind. – Jim Blackler Feb 25 '12 at 12:27
  • @JimBlackler: Yeah i realized that later but was fixed/edited by pimvdb :) – Sarfraz Feb 25 '12 at 12:29