aboutsummaryrefslogtreecommitdiff
path: root/tools/queue.js
blob: d8853e48f3117a92704547a7772321aa78aa97af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// A generalized queue object for rapid responses (doesn't do prioritization or algorithmic timesharing)
// .enable must be used to start it, and .enqueue can be used at any time

module.exports = function(delayms, maxExport, call){
  let queue = [];
  let open = true; // The meaning of this variable is complicated, so watch closely
  let getObjs = (maxExport == 1) ? // Should call be given one object or an array?
    () => queue.shift() :
    () => queue.splice(0, maxExport);

  this.enqueue = function(arr){
    for (item of arr)
      queue.push(item);
    if (open) dequeue();
  }

  disabled = true; // Used to disable pushes when non-sensical like if a socket is down
  this.disable = function(){
    disabled = true;
  }
  this.enable = function(){
    disabled = false;
    if (open) dequeue();
  }
  function dequeue(){
    if (disabled){
      open = true;
      return;
    }
    if (queue.length == 0)
      open = true;
    else {
      open = false;
      call(getObjs());
      setTimeout(dequeue, delayms);
    }
  }
}