JS实现函数节流方法

函数节流可以一定程度得减少系统的损耗,方法如下:

/**
 * 函数节流方法
 * @param {Function} fn 需要进行节流执行的函数
 * @param {Number} delay 延时执行的时间
 * @param {Number} atleast 至少多长时间触发一次
 * @return {Function} 返回节流执行的函数
 */
function throttle (fn, delay, atleast = 0) {
  let timer = null; //定时器
  let previous = 0; //记录上一次执行的时间
  
  return (...args) => {
    let now = +new Date();   //当前时间戳
    if (!previous) previous = now; // 赋值开始时间
    
    if (atleast && (now - previous) > atleast) {
      fn.apply(this, args);  //文章下面有给出该行代码的理解
      // 重置上一次开始时间为本次结束时间
      previous = now;
      timer && clearTimeout(timer);
    } else {
      timer && clearTimeout(timer); // 清除上次定时器
      timer = setTimeout(() => {
        fn.apply(this, args);
        console.log('else')
        previous = 0;
      }, delay);
    }
  }
}

 

其中 fn.apply(this,  args) 不难理解,我们通过一段代码来看:

  function person(name) {
    this.name = name;
    this.sayname = function() {
      alert(this.name)
    }
  }
  
  function student(name) {
    person.apply(this, arguments)
  }

  var studenta = new student('xiaoming')
  studenta.sayname();
此时,屏幕会出现 alert('xiaoming')的效果。

由此可见 fn.apply(this,  args) 实现了对 fn 的继承, args 需要是数组形式。

posted @ 2020-07-22 09:16  几行  阅读(1128)  评论(0编辑  收藏  举报