前言
在进行页面窗口的resize、scroll、输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负担,导致用户体验非常糟糕。此时我们可以采用debounce(防抖)和throttle(节流)的方式来减少调用频率,同时又不影响实际效果,这篇文章将主要分析函数节流。
详情参考:https://timor419.github.io/2020/08/08/JS-throttle/
介绍
函数节流:
当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
实现原理:
当触发事件的时候,我们设置一个定时器,再次触发事件的时候,如果定时器存在,就不执行,直到delay时间后,定时器执行执行函数,并且清空定时器,这样就可以设置下个定时器。
适用场景:
输入框内容校验、页面滚动请求数据等。
JS代码:
let timeout;
// 函数节流
throttle(func, thres) {
const threshhold = thres || 200;
// eslint-disable-next-line consistent-return
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {
if (func) {
func();
}
}, threshhold);
};
},
// 输入信息
inputInfo(e) {
const searchKey = e.detail.value;
const func = () => {
this.setInput(searchKey);
};
this.throttle(func)();
},
// 网络请求
setInput(searchKey) {
console.log('网络请求', searchKey);
},