防抖 debounce
触发高频事件后 n 秒内函数只执行一次,若 n 秒内高频事件再次被触发,则重新计算时间。
如:监听 input 输入,对input输入框做整合,获取输入信息n秒后进行搜索。
常见场景:
- 按钮狂点击;
- 监听输入框,文字变化后触发 change 事件;
- 用 keyup 事件触发 change 事件;
//防抖
function debounce(fn,delay = 100){ //100ms = 0.1s
let timer = null
return function(){
if(timer){
clearTimeout(timer) //重新计时
}
timer = setTimeout(() => {
fn.apply(this,arguments)
timer = null
},delay)
}
}
节流 throttle
高频事件触发,但在 n 秒内只会执行一次。所以节流会稀释函数的执行频率。
如,拖拽一个元素,要实时获取拖拽的位置,仅在 n 秒后执行一次事件,获取元素当前位置。
//节流
function throttle(fn,delay){
let timer = null
return function(){
if(timer){
return
}
timer = setTimeout(() => {
fn.apply(this,arguments)
timer = null
},delay)
}
}
throttle(function(){},500)
防抖节流区别
防抖:在n秒内只执行一次,若在n秒期间点击,则定时器重新计算。
节流:在n秒内仅执行一次。