节流
第一次点击后立即执行目标函数,在间隔时间之内,不再执行。
应用场景:频繁点击按钮时,只有第一次点击有效,在时间间隔之内,不能继续点击按钮。
const sx = function(){
console.log('闪现')
}
let 冷却 = false
function jl(){
if(冷却) return
sx()
冷却 = true
setTimeout(()=>{
冷却 = false
},2000)
}
// 生成节流函数
function throttle(fn,time){
let 冷却 = false
return (()=>{
function jl(){
if(冷却) return
fn()
冷却 = true
setTimeout(()=>{
冷却 = false
},time)
}
})
}
const sx = function(){
console.log('闪现')
}
const d = throttle(sx,2000)
d()
防抖
触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延迟执行时间。
应用场景:浏览器页面 onresize/scroll/mousemove/mousehover 等,会被频繁触发(短时间内多次触发)的时候,就需要用到防抖,或者某些点击事件,防止多次点击造成频繁请求后台。
const hc = function(){
console.log("回城成功")
}
let timer = null
function fd(){
if(timer){
clearTimeout(timer) //再次调用时,先清掉之前的定时器,再重新设置定时器
}
timer = setTimeout(()=>{
hc()
timer = null
},3000)
}
生成防抖函数
const debounce = (fn,time)=>{
let timer = null
return ((...args)=>{
if(timer !==null){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.call(undefined,...args)
timer = null
},time)
})
}
const d = debounce(hc,2000)
d()