alex
alex

Reputation: 15

Stop javascript increment at a certain value

I have coded this small script which increments a given value, in this case 200, by 1 every 3.2 seconds.

var i = 200;
function increment() {
i++;
document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}
setInterval('increment()', 3200);

I'm trying to make the script stop increasing the value once it reaches a certain point (let's say 300 for example). I'm sure it's a simple fix but I can't think up of how to go about this.

Upvotes: 1

Views: 5595

Answers (4)

Ahmed M.Osman
Ahmed M.Osman

Reputation: 121

I think you could put it in IF statement as:

var i = 200;
function increment() {
    if(i<300){
        i++
    }
}
increment();

Upvotes: 0

C.S. Rhymes
C.S. Rhymes

Reputation: 1

You could use a for loop.

var i = 200;
var max = 300;

function increment() {

    for (i < max; i++) {
        document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
    }
}
setInterval('increment()', 3200);

More info here: http://www.w3schools.com/js/js_loop_for.asp

Upvotes: -1

undefined
undefined

Reputation: 4135

You need to save the interval and then clear it:

var i = 200;

function increment() {
  if (i >= 300) {
    clearInterval(interval);
    return;
  }
  i++;
  document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}
var interval = setInterval(increment, 3200);

Note that you can pass a function name instead of using the "interval()" string notation.

Here is a fiddle (I've sped up the time so that it doens't take forever to prove a point)

Hope it helps!

Upvotes: 4

Timothy S. Van Haren
Timothy S. Van Haren

Reputation: 8966

var i = 200;

function increment() {
    if (i == 300) {
        // stop when it hits 300
        window.clearInterval(id);
        return;
    }

    i++;
    document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}

var id = window.setInterval('increment()', 3200);

Upvotes: 1

Related Questions