All files / fn regular.js

86.67% Statements 13/15
75% Branches 6/8
100% Functions 3/3
86.67% Lines 13/15

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                                              1x 1x 1x 11x 11x 11x 11x 1x 3x 3x   3x       3x           1x  
/**
 * 包装为规律触发的函数,用于降低密集事件的处理频率
 * - 在疯狂操作期间,按照规律时间间隔,来调用任务函数
 * @method fn/regular
 * @param {Function} fn 要延迟触发的函数
 * @param {Number} delay 延迟时间(ms)
 * @param {Object} [bind] 函数的 this 指向
 * @return {Function} 经过包装的定时触发函数
 * @example
 * var $regular = require('@spore-ui/kit/packages/fn/regular');
 * var comp = {
 *   countWords : function(){
 *     console.info(this.length);
 *   }
 * };
 * // 疯狂按键,每隔 200ms 才有一次按键有效
 * $('#input').keydown($regular(function(){
 *   this.length = $('#input').val().length;
 *   this.countWords();
 * }, 200, comp));
 */
 
function regular(fn, delay, bind) {
  var enable = true;
  var timer = null;
  return function () {
    bind = bind || this;
    enable = true;
    var args = arguments;
    if (!timer) {
      timer = setInterval(function () {
        Eif (typeof fn === 'function') {
          fn.apply(bind, args);
        }
        Iif (!enable) {
          clearInterval(timer);
          timer = null;
        }
        enable = false;
      }, delay);
    }
  };
}
 
module.exports = regular;