Use multiple javascript loops

2

Is there any way to run more than one setInterval () at the same time? Home In my code, if I run the interval twice, the program goes into infinite loop, and on the console I get:
[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)
    
asked by anonymous 11.04.2017 / 21:13

2 answers

2

The problem with your code is that a is a global variable. If you exchange for 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)
    
11.04.2017 / 21:17
1

The problem was that a was being played in the global context, so on the second run the identifier of the first setInterval was lost and only the second one 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)
    
11.04.2017 / 21:18