js 优化过的节流函数

149 阅读1分钟

直接上代码

  function throttle(fun, delay) {
    let oldTime = 0,
        t = null;
    return function () {
      if (t) {
        clearTimeout(t);
      }
      let args = [...arguments],
          _this = this,
        newTime = +new Date();

      if(newTime - oldTime >= delay) {
        fun.apply(_this, args);
        oldTime = +new Date();
      } else {
        t = setTimeout(() => {
          fun.apply(_this, args)
          oldTime = +new Date();;
        }, delay)
      }
    }
}

总结:不一定是最优的 但绝对是经过思考的 谢谢大家!