项目背景是一个搜索框,不能实时的监听onChange 事件去发送请求,这样会造成服务器的压力
解决思路就是用 setTimeout + clearTimeout
普通js代码如下:
/ 下面是普通的js实现,可以参考一下 // 获取input元素 var textInput = document.getElementById('test-input'); // 初始化一个定时器函数 var timeout = null; textInput.onkeyup = function (e) { // 不断重置定时器函数 clearTimeout(timeout); // 500ms内没任何其他输入,获取debounce之后的结果 timeout = setTimeout(function () { console.log('Input Value:', textInput.value); }, 500); };
react 项目中的处理:
代码如下:
let timer = null if(timer){ clearTimeout(timer) } timer = setTimeout(()=>{ fetch("http://baidu.com",{ method:'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, }).then((result)=>{ return result.json() }).then((res)=>{ console.log("F209") console.log(res) if(time>this.state.time){ this.setState({ time:time, fundList:res.fundList }) if(res.fundList===null){ this.setState({ show:0 }) }else{ this.setState({ show:1 }) } } }).catch(err=> console.log(err) ) },500)
lodash中也提供了debounce函数可以有时间看一下。