+ 防抖节流的区别
防抖的目的是为了让函数的有效代码执行一次
节流是为了降低有效代码执行的频率
<body>
<button id="btn">按钮</button>
<input type="text" id="inp">
</body>
防抖方式一
fetch('./data.json');
let timer=null;
btn.onclick = function () {
clearTimeout(timer);
timer=setTimeout(()=>{
fetch('./data.json')
},1000)
};
防抖方式二
inp.oninput = function () {
let timer=null;
//每当input框的内容发生改变的时候 执行这个函数
clearTimeout(timer);
timer=setTimeout(()=>{
console.log(this.value);
fetch('./data.json')
},1000)
}
节流方式一
const throttle = (fn, delay) => {
let flag = true;
return function () {
if (!flag) return;
flag = false;
setTimeout(() => {
flag = true
}, delay)
fn()
}
}
节流方式二
let flag = true;
btn.onclick = function () {
if (!flag) return;
flag = false;
setTimeout(() => {
flag = true
}, 10001);
fetch('./data.json')
}