aboutsummaryrefslogtreecommitdiff
path: root/tools/queue.js
blob: f45ec802dff513fd99179577539b74902b4e06f8 (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
39
40
41
// 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 id = 0;
  let open = true; // Has call() run in the past delayms ms?
  let getObjs = (maxExport == 1) ? // Should call be given one object or an array?
    () => queue.shift() :
    () => queue.splice(0, maxExport);

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

  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(), id-queue.length);
      setTimeout(dequeue, delayms);
    }
  }
}