-2

I got small problem with my script

She looks like this:

i = 0;

setInterval(function() {
 
 if(i < 100) {
  i++;
 }
 
}, 1000);

if(i == 100) {
  alert("done");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

But alert doesn't work after incrementing to 100. Why? How can i do that?

k4meal
  • 1
  • 6
  • 3
    The `alert()` call will have to be **inside** the interval handler, and it should also cancel the timer. – Pointy Dec 29 '17 at 14:20
  • 1
    setInterval is asynchronous, so `if(i == 100)` is checked first before even incrementing it to 100. so, put that checking code inside setInterval. – palaѕн Dec 29 '17 at 14:23
  • You may have a look at https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop – Jonas Wilms Dec 29 '17 at 14:27

2 Answers2

3

Because of if(i < 100) that says untill the i is 99 or less.

If you need to increment till 100 use if(i <= 100) which is 100 or less.

ino
  • 2,345
  • 1
  • 15
  • 27
0

When if(i == 100) condition is executed the value of i is 0, which is incremented inside the setInterval function but no way if(i == 100) knows that.So put this condition inside the setTimeout function

var i = 0;

var _int = setInterval(function() {

  if (i < 100) {
    i++;
  }
  if (i == 100) {
    alert("done");
    clearInterval(_int)
  }

}, 40);
brk
  • 48,835
  • 10
  • 56
  • 78