All files / util job.js

100% Statements 19/19
91.67% Branches 11/12
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                  1x   1x   1x 3x 3x       3x     1x 6x 3x 3x 3x 3x 2x   3x 3x           3x 3x     1x  
/**
 * 任务分时执行
 * - 一方面避免单次reflow流程执行太多js任务导致浏览器卡死
 * - 另一方面单个任务的报错不会影响后续任务的执行
 * @method util/job
 * @param {Function} fn 任务函数
 * @returns {Object} 任务队列对象
 * @example
 * var $job = require('@spore-ui/kit/packages/util/job');
 * $job(function() {
 *   //task1 start
 * });
 * $job(function() {
 *   //task2 start
 * });
 */
 
var manager = {};
 
manager.queue = [];
 
manager.add = function (fn, options) {
  options = options || {};
  manager.queue.push({
    fn: fn,
    conf: options,
  });
  manager.step();
};
 
manager.step = function () {
  if (!manager.queue.length || manager.timer) { return; }
  manager.timer = setTimeout(function () {
    var item = manager.queue.shift();
    Eif (item) {
      if (item.fn && typeof item.fn === 'function') {
        item.fn.call(null);
      }
      manager.timer = null;
      manager.step();
    }
  }, 1);
};
 
function job(fn, options) {
  manager.add(fn, options);
  return manager;
}
 
module.exports = job;