0

The code:

for(var a=0;a<=60;a++){
    setTimeout(function(){
        document.getElementById("a").innerHTML=a;
    },1000);
}

It displays 61 with no delay at all. I can not see any reason why it would do that...

user3077458
  • 131
  • 1
  • 4
  • Are you sure it didn't wait 1 second before displaying 61? You have 60 functions that all run at the same time, 1 second after the loop. – Barmar Mar 04 '15 at 20:18
  • What you are trying to achieve is setInterval implementation. – roshan Mar 04 '15 at 20:20
  • 1
    I see that this question has been marked as a duplicate, but I looked at the question/answer that was referred to, and I do not share the same conclusion as @alexander. The reason you are not getting a delay is because setTimeout will call the function once before delaying and calling again. You need to get rid of the for loop and, instead, have a counter increment within the setTimeout method. I would give a clean example of this, but I unable to because of the question being marked as a duplicate. – Patrick Smith Mar 04 '15 at 20:26

1 Answers1

0

What you are trying to achieve is clearly an implementation of setInterval.

  var a = 0;

  function displayIncreament() {
    if (a <= 60) {
      document.getElementById("a").innerHTML = a;
      a++;
    } else {
      clearInterval(IncreamentInterval)
    }

  }

  var IncreamentInterval = setInterval(displayIncreament, 1000)
<span id="a"></span>
roshan
  • 2,410
  • 2
  • 25
  • 37