1、第一种
debounce (func, delay) {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
// this,
func.apply(this, args)
}, delay)
}
}
2、第二种
<body>
<input type="text" id="input">
<!--
1、防抖函数的理解
1、当持续触发事件,一定时间内没有再触发事件,事件处理函数才会执行一次(定时器)
2、如果设定的时间到来之前,又一次触发了事件,就重新开始延时
(意味着上一次还没有结束掉的定时器要清除掉,重新开始)
-->
<script>
// 防抖函数
// 实际开发中的应用
// 一般是做搜索的时候使用
function debounce(fun,delay){
let timer;
return function(args){
clearInterval(timer);
timer = setTimeout(function(){
fun(args);
},delay)
}
}
/*// 这样在外面调用debounce 函数,就会返回
function(){clearInterval(timer);
timer = setTimeout(function(args){
fun(args);
},delay)
}
这个函数,返回的这个函数里面始终保存着timer 这个变量,就能达到缓存的目的
*/
function inputFun(value){
console.log(`你输入的结果是${
value}`);
}
const input = document.getElementById("input");
const debounceInput = debounce(inputFun,1000);
input.addEventListener('keyup',function(e){
debounceInput(e.target.value);
})
</script>
</body>