1 | ;
|
2 |
|
3 | exports.__esModule = true;
|
4 | exports.asap = asap;
|
5 | exports.suspend = suspend;
|
6 | exports.flush = flush;
|
7 | var queue = [];
|
8 | /**
|
9 | Variable to hold a counting semaphore
|
10 | - Incrementing adds a lock and puts the scheduler in a `suspended` state (if it's not
|
11 | already suspended)
|
12 | - Decrementing releases a lock. Zero locks puts the scheduler in a `released` state. This
|
13 | triggers flushing the queued tasks.
|
14 | **/
|
15 | var semaphore = 0;
|
16 |
|
17 | /**
|
18 | Executes a task 'atomically'. Tasks scheduled during this execution will be queued
|
19 | and flushed after this task has finished (assuming the scheduler endup in a released
|
20 | state).
|
21 | **/
|
22 | function exec(task) {
|
23 | try {
|
24 | suspend();
|
25 | task();
|
26 | } finally {
|
27 | release();
|
28 | }
|
29 | }
|
30 |
|
31 | /**
|
32 | Executes or queues a task depending on the state of the scheduler (`suspended` or `released`)
|
33 | **/
|
34 | function asap(task) {
|
35 | queue.push(task);
|
36 |
|
37 | if (!semaphore) {
|
38 | suspend();
|
39 | flush();
|
40 | }
|
41 | }
|
42 |
|
43 | /**
|
44 | Puts the scheduler in a `suspended` state. Scheduled tasks will be queued until the
|
45 | scheduler is released.
|
46 | **/
|
47 | function suspend() {
|
48 | semaphore++;
|
49 | }
|
50 |
|
51 | /**
|
52 | Puts the scheduler in a `released` state.
|
53 | **/
|
54 | function release() {
|
55 | semaphore--;
|
56 | }
|
57 |
|
58 | /**
|
59 | Releases the current lock. Executes all queued tasks if the scheduler is in the released state.
|
60 | **/
|
61 | function flush() {
|
62 | release();
|
63 |
|
64 | var task = void 0;
|
65 | while (!semaphore && (task = queue.shift()) !== undefined) {
|
66 | exec(task);
|
67 | }
|
68 | } |
\ | No newline at end of file |