用防抖,节流来优化性能

看文章时了解了防抖,节流两个概念,觉得可以优化项目中输入框输入内容时多次调用接口的问题。
防抖: 开始输入内容时设定一个计时器,如果在计时器之内又有内容则不调用接口,重新开始计时

<input type="text" class="form-control" [(ngModel)]="seoCon" (keyup)="onBounce()" placeholder="Search for...">
 // 输入事件
  onBounce() {
    // console.log(this.seoCon);
    let debounceAjax = this.debounce(this.ajax, 3000);
    debounceAjax(this.seoCon);
  }
  // 防抖
  debounce(fun, delay) {
    return function (args) {
      //获取函数的作用域和变量
      let that = this
      let _args = args
      //每次事件被触发,都会清除当前的timer,然后重写设置超时调用
      clearTimeout(fun.id);
      fun.id = setTimeout(function () {
          fun.call(that, _args);
      }, delay);
    };
  }
  // 请求
  ajax(content) {
    console.log('ajax request ' + content);
  }

节流: 规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。

// 输入事件
onBounce() {
  // console.log(this.seoCon);
  let throttleAjax = this.throttle(this.ajax, 2000);
  throttleAjax();
}
throttle(fun, delay) {
    let that = this;
    return function (args) {
      that.deferTimer = setTimeout(() => {
        fun.apply(that);
      }, delay);
    };
  }
ajax() {
    if (this.deferTimer) {
      console.log('ajax request ' + this.seoCon);
      this.deferTimer = null;
      clearTimeout(this.deferTimer);
    }
 }

效果对比如下:
在这里插入图片描述
在这里插入图片描述

延伸问题:
1、执行上下文(this):
函数嵌套时this指向问题

2、call() / apply() / bind()
这三个都是调用函数时,可以改变函数内部的this指向,并传入一些值

func.call(this, arg1, arg2); // 使用 call,参数列表
func.apply(this, [arg1, arg2]) // 使用 apply,参数数组
func.bind(this, arg1, arg2); // 使用 bind,参数列表
用法和call一样,区别在于call立即执行,bind等待执行

注意: 页面销毁时记得把计时器销毁,否则造成内存泄露,影响性能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值