防抖
什么是防抖?先看一段代码
<body>
<input type="text" name="" id="">
</body>
<script>
let inp = document.querySelector("input");
inp.oninput = function(){
console.log(this.value);
}
</script>
这段代码在屏幕显示一个input框,并在input输入时在控制台输出。
可以观察控制台,仅仅输入四个字,事件却执行了很多次,这是很影响效率的。那么我们怎么样才能让请求的次数没有那么多呢?
这时候就要采用防抖了,防抖就是在当用户触发事件过于频繁时,只要最后一次的事件操作。
<body>
<input type="text" name="" id="">
</body>
<script>
let inp = document.querySelector("input");
let t = null;
inp.oninput = function () {
if (t !== null) {
clearTimeout(t);
}
t = setTimeout(() => {
console.log(this.value);
}, 500)
}
</script>
附一个封装好的防抖函数
/**
* @desc 函数防抖
* @param func 函数
* @param wait 延迟执行毫秒数
* @param immediate true 表立即执行,false 表非立即执行
*/
function debounce(func,wait,immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
}