Use multiple javascript loops

Asked

Viewed 66 times

2

Is there any way to run more than one setInterval() at the same time?
In this my code, if I run twice the function "interval" the program goes into infinite loop and the console gets:
[1,2,3,4,5]
[1,2,3,4,5,6]
[1,2,3,4,5,6,7]
[1,2,3,4,5,6,7,8......] infinitely

arraya = []
arrayb = []
function interval(array, length, count) {
    a = setInterval(function () {
        count++;
        array.push(count);
        if (array.length > length) {
            console.log(array.join(' '));
            clearInterval(a);
        }
    }, 150);;
}
interval(arraya, 4, 0);
// interval(arrayb, 9, 0)

  • It seemed to me a kind of similar doubt: http://answall.com/questions/178944/existe-um-modo-de-cria-uma-execu%C3%A7%C3%A3o-parallel-using-javascript

2 answers

2


The problem with your code is that a is a global variable. If you switch to a local variable everything works fine.

arraya = []
arrayb = []
function interval(array, length, count) {
    var a = setInterval(function () {
        count++;
        array.push(count);
        if (array.length > length) {
            console.log(array.join(' '));
            clearInterval(a);
        }
    }, 150);;
}
interval(arraya, 4, 0);
interval(arrayb, 9, 0)

  • It worked :) thank you so much for your help! I will test on other programs later.

  • @anobeginnerther10 hello and welcome. I think it’s important to see this: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-accepta reply

1

the problem was that the a was being played in the global context, soon in the second execution the identifier of the first setInterval was lost and only the second stopped, just add var before a to solve this

arraya = []
arrayb = []
function interval(array, length, count) {
    var a = setInterval(function () {
        count++;
        array.push(count);
        if (array.length > length) {
            console.log(array.join(' '));
            clearInterval(a);
        }
    }, 150);;
}
interval(arraya, 4, 0);
interval(arrayb, 9, 0)

Browser other questions tagged

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