目录
问题引入:
定义
解决方案:函数节流
一、案例举例
1.页面展示
2.search.wxml标签展示
3.search.js展示
4.结果展示
二、函数节流解决问题
1.函数
2.实例应用
三、函数防抖解决问题
1.函数
2.原理
3.应用场景
4.应用实例
总结
问题引入:
在搜索框中,程序短时间内大量触发某函数而导致的性能下降。
定义
- 节流: n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效
 - 防抖: n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
 
解决方案:函数节流
- 函数节流: 频繁触发,但只在特定的时间内才执行一次代码
 - 函数防抖: 频繁触发,但只在特定的时间内没有触发执行条件才执行一次代码
 
一、案例举例
1.页面展示

2.search.wxml标签展示
<input type="text"  bindinput="handleInputChange" /> 
3.search.js展示
handleInputChange(event){
    console.log(event.detail.value)
} 
4.结果展示

二、函数节流解决问题
1.函数
setTimeout(() => {
   
}, 300); 
2.实例应用
//全局变量
let isSend = false;
// input 输入框
handleInputChange(event) {
    console.log(event.detail.value)
    this.setData({
      searchContent: event.detail.value.trim()
    });
    // 函数节流 防抖
    if (isSend) {
      return
    }
    isSend = true
    this.getSearchList()
    setTimeout(async () => {
      isSend = false
    }, 300);
  },
//请求方法
async getSearchList() {
    let searchListData = await request('/search', { keywords: this.data.searchContent, limit: 10 })
    this.setData({
      searchList: searchListData.result.songs
    })
  }, 
三、函数防抖解决问题
1.函数
debounce: function (func, wait) {
    
    return () => {
      clearTimeout(timer);
      timer = setTimeout(func, wait);
    };
};
func:需要防抖的函数;
wait:number类型,setTimeout的时间参数;
 
2.原理
防抖的原理就是:你尽管触发事件,但是我一定在事件触发n秒无操作后才执行
3.应用场景
- 表单验证
 - 搜索框输入查询
 - 滚动条滚动
 - 按键提交
 
4.应用实例
function debounce(fn, interval) {
    let timer;
    let delay = interval || 500; // 间隔的时间,如果interval不传,则默认1秒
    return function () {
        let that = this;
        let args = arguments; // 保存此处的arguments,因为setTimeout是全局的,arguments不是防抖函数需要的。
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            fn.apply(that, args); // 用apply指向调用debounce的对象,相当于this.fn(args);
        }, delay);
    };
}
 
总结
- 函数节流与函数防抖节约计算机资源,提升用户体验
 - 节流一般是用在必须执行这个动作,但是不能够执行太频繁的情况下
 - 防抖一般是用来,用户输入有操作时,暂时不执行动作,等待没有新操作时,进行相应响应
 - 函数防抖与节流都可以解决频繁使用计算机资源的问题
 



















