看文章时了解了防抖,节流两个概念,觉得可以优化项目中输入框输入内容时多次调用接口的问题。
防抖: 开始输入内容时设定一个计时器,如果在计时器之内又有内容则不调用接口,重新开始计时
<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等待执行
注意: 页面销毁时记得把计时器销毁,否则造成内存泄露,影响性能