🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
简单的理解方式就是:用户多次触发事件,在用户一直触发事件中,事件不会执行,只有在用户停止触发事件一段时间之后再执行这个事件一次。 ``` /** * @description 防抖函数 * @param {传入的方法} fn * @param {延时时间} delay */ const debounce = (fn, delay = 300)=>{ let timer = null; return function debounce(...args) { return new Promise((resolve, reject) => { clearTimeout(timer); timer = setTimeout(() => { try { resolve(fn.apply(this, args)) } catch (e) { reject(e) } }, delay); }) } } //导出 module.exports = { debounce } ``` ``` 在wxs中引入 import {debounce} from '../../utils/util' //getSearchSuggest是接口调用方法,500ms只触发一次 const debounceFun = debounce(getSearchSuggest,500); debounceFun(val.detail).then(res => { if (res.code == 200) { this.setData({ searchSuggest: res.result.allMatch.splice(0, 10) }) } }) ``` 效果图:不会每次输入完就调接口 ![](https://img.kancloud.cn/59/2d/592d89d59a8c4a85ed89dbf070eabed4_575x465.png)