1 |
|
2 |
|
3 | var Type = require('./type');
|
4 | function s(state, cb, time){
|
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 | }
|
10 | s.waiting = [];
|
11 | s.soonest = Infinity;
|
12 | s.sort = Type.list.sort('when');
|
13 | s.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 | }
|
20 | s.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 | }
|
32 | s.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 | }
|
38 | module.exports = s;
|
39 | |
\ | No newline at end of file |