UNPKG

1.85 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(require) {
7
8 var Queue = require('./Queue');
9
10 // Credit to Twisol (https://github.com/Twisol) for suggesting
11 // this type of extensible queue + trampoline approach for next-tick conflation.
12
13 /**
14 * Async task scheduler
15 * @param {function} async function to schedule a single async function
16 * @constructor
17 */
18 function Scheduler(async) {
19 this._async = async;
20 this._queue = new Queue(15);
21 this._afterQueue = new Queue(5);
22 this._running = false;
23
24 var self = this;
25 this.drain = function() {
26 self._drain();
27 };
28 }
29
30 /**
31 * Enqueue a task
32 * @param {{ run:function }} task
33 */
34 Scheduler.prototype.enqueue = function(task) {
35 this._add(this._queue, task);
36 };
37
38 /**
39 * Enqueue a task to run after the main task queue
40 * @param {{ run:function }} task
41 */
42 Scheduler.prototype.afterQueue = function(task) {
43 this._add(this._afterQueue, task);
44 };
45
46 /**
47 * Drain the handler queue entirely, and then the after queue
48 */
49 Scheduler.prototype._drain = function() {
50 runQueue(this._queue);
51 this._running = false;
52 runQueue(this._afterQueue);
53 };
54
55 /**
56 * Add a task to the q, and schedule drain if not already scheduled
57 * @param {Queue} queue
58 * @param {{run:function}} task
59 * @private
60 */
61 Scheduler.prototype._add = function(queue, task) {
62 queue.push(task);
63 if(!this._running) {
64 this._running = true;
65 this._async(this.drain);
66 }
67 };
68
69 /**
70 * Run all the tasks in the q
71 * @param queue
72 */
73 function runQueue(queue) {
74 while(queue.length > 0) {
75 queue.shift().run();
76 }
77 }
78
79 return Scheduler;
80
81});
82}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));