How to increment from 0 to 10 inside a Javascript setInterval

Asked

Viewed 286 times

2

setInterval(function()
{
    var x = 0; 
    x++; 
    console.log(x);},
    1000);
}
  • You can explain what functionality you want to achieve?

  • Managed to solve the problem?

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);

1

Another option is to use setTimeout to simulate the behaviour 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;
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.