防抖与节流
1. 防抖就是用户多次触发事件 但是只执行最后的一次
2. 设置debounce函数 返回一个函数 利用闭包的思想 在外层函数设置定时器id 内层函数设置定时器 在最开始清除定时器 然后一定时间间隔执行事件 return的函数的this和event是要执行函数的 所以在外面设置变量 交给定时器内部的函调函数 改变event和this
let btn = document.getElementById('btn');
function debounce(fun, delay) {
let timer;
return function () {
let args=arguments;
clearTimeout(timer);
timer=setTimeout(()=>{
fun.apply(this, args);
},delay)
}
}
btn.onclick = debounce(function (e) {
console.log(this, e);
}, 300)
4. 节流是多次触发 减少执行的次数
设置throttle函数 先设置一个开始的时间戳为0 return一个函数 里面设置现在的时间戳为now 相差大于delay才执行,执行完设置开始时间戳为now
function throttle(fun, delay) {
let before = 0;
return function () {
let context = this;
let args = arguments;
let now = new Date().valueOf();
if (now - before > delay) {
fun.apply(context, args);
before = now;
}
}
}
另一种方法:设置timer=true 在定时器回调里设置timer=true 在外面设置timer=false
function throttle(fun, delay) {
timer = true;
return function () {
let context = this;
let args = arguments;
if (timer) {
timer = setTimeout(() => {
fun.apply(context, args);
timer = true;
}, delay)
}
timer=false;
}
}
```