js节流代码的疑问

看到一个实现节流的方法,但是其中有两个地方不太理解。

export function throttle(fn,delay){
    var lastTime;
    var timer;
    var delays = delay || 200;
    console.log('页面创建是就被打印出来',delays,arguments)
    return function() {
      var args = arguments;
      console.log(this,arguments)
      // 记录当前函数触发的时间
      var nowTime = Date.now();
      if (lastTime && nowTime - lastTime < delays) {
        clearTimeout(timer);
        timer = setTimeout(function () {
          // 记录上一次函数触发的时间
          lastTime = nowTime;
          // 修正this指向问题
          fn.apply(this, args);
        }, delays);
      }else{
        lastTime = nowTime;
        fn.apply(this, args);
      }
    }
  } 
// 调用方法
  import { throttle } from "../../utils";
  methods: {
    onAdd: throttle(function(i) {
      this.num += i;
    }, 3000)
  }

我试了一下,发现在页面创建后就会打印出第一条内容。触发onAdd时只执行retyrn function中的内容,这是为什么?
第二个问题:在定时器里为什么还要写apply方法,而且这一步还没被执行?

待解决 悬赏分:30 - 离问题结束还有 278天13小时39分38秒
反对 0举报 0 收藏 0

我来回答

回答3