在一定时间内,只执行最后一次任务。
在事件被触发的 N 秒后再执行任务(回调函数),如果在这 N 秒内又触发事件,则重新计时:
防抖的应用场景:
手写实现防抖:
var btn=document.querySelector('button')
var ipt=document.querySelector('input')
btn.addEventListener('click',debounce(getValue,2000))
function getValue(){
var val=ipt.value
console.log(val);
}
function debounce(fn,time){
let t=null
return function(){
if(t){
clearTimeout(t)
}
var firstClick=!t
if(firstClick){
fn.apply(this,arguments)
}
t=setTimeout(() => {
t=null
}, time);
}
}
在一定时间内,同一个任务只会执行一次。
在一定时间内,只能触发一次响应函数,如果事件频繁触发,只有一次生效。
节流的应用场景:
var btn=document.querySelector('button')
var ipt=document.querySelector('input')
btn.addEventListener('click',throttle(getValue,2000))
function getValue(){
var val=ipt.value
console.log(val);
}
function throttle(fn,time){
var begin=0
return function(){
var date=new Date().getTime()
if(date-begin>time){
fn.apply(this,arguments)
begin=date
}
}
}