UNPKG

1.05 kBJavaScriptView Raw
1
2// Generic javascript scheduler utility.
3var Type = require('./type');
4function s(state, cb, time){ // maybe use lru-cache?
5 s.time = time || Gun.time.is;
6 s.waiting.push({when: state, event: cb || function(){}});
7 if(s.soonest < state){ return }
8 s.set(state);
9}
10s.waiting = [];
11s.soonest = Infinity;
12s.sort = Type.list.sort('when');
13s.set = function(future){
14 if(Infinity <= (s.soonest = future)){ return }
15 var now = s.time();
16 future = (future <= now)? 0 : (future - now);
17 clearTimeout(s.id);
18 s.id = setTimeout(s.check, future);
19}
20s.each = function(wait, i, map){
21 var ctx = this;
22 if(!wait){ return }
23 if(wait.when <= ctx.now){
24 if(wait.event instanceof Function){
25 setTimeout(function(){ wait.event() },0);
26 }
27 } else {
28 ctx.soonest = (ctx.soonest < wait.when)? ctx.soonest : wait.when;
29 map(wait);
30 }
31}
32s.check = function(){
33 var ctx = {now: s.time(), soonest: Infinity};
34 s.waiting.sort(s.sort);
35 s.waiting = Type.list.map(s.waiting, s.each, ctx) || [];
36 s.set(ctx.soonest);
37}
38module.exports = s;
39
\No newline at end of file