How to increment from 0 to 10 within a setInterval in JavaScript

2
setInterval(function()
{
    var x = 0; 
    x++; 
    console.log(x);},
    1000);
}
    
asked by anonymous 13.04.2016 / 06:35

2 answers

4

You can call clearInterval() after 10 calls:

var x = 0;
var intervalo = setInterval(function () {
   console.log(x);
    if (++x === 10) {
        window.clearInterval(intervalo);
    }
 }, 1000);

If you want to avoid global variables, a good improvement would be:

function setIntervalo(delay, iteracoes) {
    var x = 0;
    var intervalo = window.setInterval(function () {

       console.log(x);

       if (x++ === iteracoes) {
           window.clearInterval(intervalo);
       }
    }, delay);
}

Then just call setInvervalo :

setIntervalX(1000, 10);
    
13.04.2016 / 06:55
1

Another option is to use setTimeout to simulate the behavior of setInterval and have a function that determines when it should end.

function setIntervalDelayed(delay, interval, cb){
    setTimeout(function(){
        if(cb()){
            setIntervalDelayed(interval, interval, cb);
        }
    }, delay);
}

setIntervalDelayed(0, 1000, function(){
    return x++ != 10;
})
    
13.04.2016 / 10:58