Scheduler.js 1.7 KB

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