setInterval(function()
{
var x = 0;
x++;
console.log(x);},
1000);
}
setInterval(function()
{
var x = 0;
x++;
console.log(x);},
1000);
}
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);
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;
})