I recently had an interesting requirement in a test environment where I needed to simulate actions at varied (random) intervals in a node
back-end. They needed to be sequentially executed, but queued so I could fire and move on. Using a typical timeout/interval here wouldn't work, since if I set a timeout for fn1
to execute after 500ms and then set a timeout for fn2
to execute after 250ms, fn2
would execute before fn1
, which was not desired.
To solve this, I created a queue object that executes queued commands sequentially. It works perfectly for my scenario, but I was wondering if there were any opportunities for improvement. I realize I should probably be checking input parameters to make sure the passed in function is indeed a function, as well as the delay being a number. Maybe there are other opportunities for improvement. Let me know!
var TimerQueue = (function () {
var timers = [];
var running = false;
var currentInterval;
var currentTimer;
this.addTimer = function (fn, delay) {
timers.push({fn: fn, delay: delay});
function exec() {
currentTimer.fn();
clearInterval(currentInterval);
if (timers.length > 0) {
currentTimer = timers.shift();
currentInterval = setInterval(exec, currentTimer.delay);
} else {
running = false;
}
}
if (!running) {
running = true;
currentTimer = timers.shift();
currentInterval = setInterval(exec, currentTimer.delay);
}
};
this.clear = function () {
if (currentInterval) {
clearInterval(currentInterval);
}
timers = [];
running = false;
};
return this;
});
Usage:
var queue = new TimerQueue();
queue.addTimer(function () { console.log('1st') }, 500);
queue.addTimer(function () { console.log('2nd') }, 250);
500
timer and a250
timer, should the second function wait 750 ms or 500? \$\endgroup\$