一、 防抖(debounce )
作用:对在短时间内多次触发事件的回调函数,只执行最后一次,或者只在最开始时执行。
假设场景: 1.当输入框搜索内容时,只有当用户输入完才与后端接口交互
// 原始版本
var inp = document.querySelector('input');
var t = ''
inp.onpinput = function(){
if(t!==null){
clearTimeout(t)
}
t = setTimeout(() => {
console.log(this.value)
}, 500);
}
// 简单封装
function debounce(fn, delay) {
var t = null;
return function() {
if (t !== null) {
clearTimeout(t);
}
t = setTimeout(() => {
fn();
}, delay);
};
}
执行:
window.addEventListener('resize',debounce(()=>{console.log('执行了')},2000));
二、节流(throttling )
作用:类似于防抖,不过节流是在一段时间之内只允许该函数执行一次
// 原始版本
var flag =true
function throttling(){
if(flag){
setTimeout(()=>{
console.log('执行了')
flag =true
},500)
}
flag =false
// 简单封装
function throttling(fn, delay) {
var flag = true;
return function() {
if (flag) {
setTimeout(()=>{
fn.call()
flag =true
},500)
}
flag =false
};
}
执行:
window.addEventListener('resize',throttling(()=>{console.log('执行了')},2000));