1

This loop is in a function and it counts down from 10, however if I alert the parameter passed using i in the setV function it actually counts up!

for (var i=10;i>0;i--){
setTimeout('setV('+i+',"Out")',100);
}


function setV(c,t){
alert(c);
}
8
  • If you're doing alert(i), it doesn't count up. It should give you 0 for every alert, because that's the value of i when the setTimeout callbacks run. Commented Nov 23, 2012 at 17:36
  • @user1689607 not really. The value is captured by string concatenation. Commented Nov 23, 2012 at 17:37
  • All of those fire right after each other, and in reverse order (10,9,8,7,6...). What's the problem? Commented Nov 23, 2012 at 17:37
  • @JanDvorak: OP is talking about alerting i. Unless I'm misunderstanding the point. Commented Nov 23, 2012 at 17:37
  • @user1689607 he alerts the first argument, which gets its value from i. Commented Nov 23, 2012 at 17:39

3 Answers 3

4

All the setV are programmed to execute at the same time (100ms after the instaneous loop execution), the order isn't determined (see the spec).

You probably wanted

for (var i=10;i>0;i--){
   setTimeout('setV('+i+',"Out")',100*(11-i));
}
Sign up to request clarification or add additional context in comments.

20 Comments

so I can't use a for loop to trigger the animation frames?
I edited : to have the same order you should use 100*(11-i) (or (10-i) to have it start immediately.
@user1209203 The reason it counts "the wrong way" is because a callback set for 100ms fires before one set for 200ms and so forth
The order isn't determined? Even though the duration is the same, the order will be maintained... unless you can show a working demo that suggests otherwise,.
@Asad That example is flawed, because the timeout values are not identical.
|
0

If you are describing the behavior with:

setTimeout('setV('+i+',"Out")',i*100);

the reason it counts up is because a callback set for 1s will execute earlier than one set for 2s, which will execute earlier than one set for 3s...

Comments

0

When all of the timeouts are set to run at the same time, there is no promise what order they will run this.

This is a much better way to write that loop:

  function initThis() {
    var idx = 0;
    function doOneIteration() {
      window.alert(idx);
      idx++;
      if (idx <= 10) {
        window.setTimeout(doOneIteration);
      }
    }
    doOneIteration(); // Start loop
  }  


  initThis();  // This makes it all happen

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.