防抖 (debounce)
- 防抖 当持续触发事件 一定时间内没有再触发事件 下次的事件处理函数会再次执行 如果设定时间内再次触发了该函数 则 函数会重新开始计时
- 就是让触发事件在n秒内只执行一次,一般用定时器来设置防抖函数
// 将变量作用域提在最外层
let times
// 防抖函数
debounce = (timer,fn)=>{
// 每次进来时 是上一次的timer清除上次后 在 timer时间内没有再次触发 则会执行函数 否则会继续清除
clearTimeout(times)
times = setTimeout(()=>{
fn()
},timer)
}
input.addEventListener('keydown',(e)=>{
debounce(1000,()=>{
div.innerText = input.value
console.log(input.value)
})
})
// 一般用于 模糊查询 改变浏览器宽度
封装函数
// 需要将变量一直存储在内存当中 使用闭包来解决
debounce = (timer) => {
let times
return (fn) => {
clearTimeout(times)
times = setTimeout(() => {
fn()
}, timer)
}
}
let deinput = debounce(1000)
input.addEventListener('keydown', (e) => {
deinput(() => {
div.innerText = input.value
console.log(input.value)
})
})
节流 (throttle)
节流 防止事件在同一时间内多次触发 一般在触发后n秒内再触发下一次 防止重复点击和重复提交
throttle = (wait)=>{
let timeOut;
return (fn)=>{
//相当于在开始启动服务 第二次setTimeout不执行
if(!timeOut){
timeOut = setTimeout(() => {
fn()
timeOut = null
}, wait);
console.log(timeOut)
}
}
}
let c = throttle(400)
div.addEventListener('click',(e)=>{
c(add)
})
function add(){
ss.innerText = a
a++
}
throttle = ()=>{
let timeOut;
return (fn)=>{
//返回 Promise 对象
return new Promise((res,rej)=>{
console.log(timeOut)
if(!timeOut){
console.log(timeOut)
timeOut = setTimeout(() => {
res(fn)
timeOut = null
}, 1000);
}
console.log(timeOut,2)
})
}
}
let c = throttle()
div.addEventListener('click',(e)=>{
// c(add)
c(add).then(res=>{
res()
})
})
function add(){
ss.innerText = a
a++
}