UNPKG

1.77 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2010-2014 original author or authors */
2/** @author Brian Cavalier */
3/** @author John Hann */
4
5(function(define) { 'use strict';
6define(function() {
7
8 // Credit to Twisol (https://github.com/Twisol) for suggesting
9 // this type of extensible queue + trampoline approach for next-tick conflation.
10
11 /**
12 * Async task scheduler
13 * @param {function} async function to schedule a single async function
14 * @constructor
15 */
16 function Scheduler(async) {
17 this._async = async;
18 this._running = false;
19
20 this._queue = this;
21 this._queueLen = 0;
22 this._afterQueue = {};
23 this._afterQueueLen = 0;
24
25 var self = this;
26 this.drain = function() {
27 self._drain();
28 };
29 }
30
31 /**
32 * Enqueue a task
33 * @param {{ run:function }} task
34 */
35 Scheduler.prototype.enqueue = function(task) {
36 this._queue[this._queueLen++] = task;
37 this.run();
38 };
39
40 /**
41 * Enqueue a task to run after the main task queue
42 * @param {{ run:function }} task
43 */
44 Scheduler.prototype.afterQueue = function(task) {
45 this._afterQueue[this._afterQueueLen++] = task;
46 this.run();
47 };
48
49 Scheduler.prototype.run = function() {
50 if (!this._running) {
51 this._running = true;
52 this._async(this.drain);
53 }
54 };
55
56 /**
57 * Drain the handler queue entirely, and then the after queue
58 */
59 Scheduler.prototype._drain = function() {
60 var i = 0;
61 for (; i < this._queueLen; ++i) {
62 this._queue[i].run();
63 this._queue[i] = void 0;
64 }
65
66 this._queueLen = 0;
67 this._running = false;
68
69 for (i = 0; i < this._afterQueueLen; ++i) {
70 this._afterQueue[i].run();
71 this._afterQueue[i] = void 0;
72 }
73
74 this._afterQueueLen = 0;
75 };
76
77 return Scheduler;
78
79});
80}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));