Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequentially running multiple setIntervals

I'm trying to run multiple setInterval()'s but I'm having trouble with the asynchronous aspect of doing this.

This example is almost identical to what I'm trying to achieve:

var labels = ["Bacon", "Beer", "Steak"];
var second, timer;
labels.forEach(function(label){
    second = 0;
    timer = setInterval(function(){
        console.log(label + ' is awesome ' + second);
        if(second === 10) {
            clearInterval(timer);
        }
        second++;
    }, 1000);
});

Because of setInterval being asynchronous the three intervals are running in parallel and are messing up the interval:

Bacon is awesome 0

Beer is awesome 1

Steak is awesome 2

Beer is awesome 3

Bacon is awesome 4

Steak is awesome 5

Bacon is awesome 6

Beer is awesome 7

Steak is awesome 8

Bacon is awesome 9

Beer is awesome 10

Beer is awesome 11

Bacon is awesome 12

Beer is awesome 13

Bacon is awesome 14

Bacon is awesome 15

Beer is awesome 16

Beer is awesome 17

Bacon is awesome 18

Bacon is awesome 19

Beer is awesome 20

Beer is awesome 21

Bacon is awesome 22

Bacon is awesome 23

...

I'm wondering how to enforce some sort of queue so that the first interval runs it's course then when 10 seconds are up the next setInterval is executed?

I've tried quickly with the async.js library but I had trouble finding a suitable control flow.

like image 779
iamjonesy Avatar asked Feb 18 '26 01:02

iamjonesy


1 Answers

I made a little function called `callQueue' that calls an Array filled with functions in order a certain number of times with a certain interval between them

Usage

The first argument is the array of functions, the second the number of times they should be called, the third is the time between the calls.

callQueue([

function () {
    isAwesome('bacon');
},

function () {
    isAwesome('beer');
},

function () {
    isAwesome('steak');
}], 10, 1000);

The Function

function callQueue(queue, times, timeBetween) {
    var i = 0;
    k = 0;
    queue.forEach(function (func) {
        for (k = 0; k < times; k += 1) {
            alert(i * timeBetween);
            i += 1;
            setTimeout(func, (i * timeBetween));
        }
    });
};

Demo: http://jsfiddle.net/howderek/L5nhU/

like image 188
howderek Avatar answered Feb 20 '26 14:02

howderek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!