节流
n秒内只运行一次,若在 n 秒内重复触发,只有一次生效
- 时间戳方式
function throttle(fn, interval=300) {
let oldTime = Date.now()
return function(..args){
let newTime = Date.now()
if(newTime - oldTime >= interval){
fn.apply(this, args)
oldTime = newTime
}
}
}
- setTimeout 方式
function throttle2(fn, interval){
let timer
return function(...args){
if(!timer){
timer = setTimeout(()=>{
fn.apply(this, args)
timer = null
}, interval)
}
}
}
防抖
n 秒后触发,若在 n 秒内触发,重新计时
function debounce(fn, delay){
let timer
return function(){
const context = this
const args = arguments
if(timer){clearTimeout(timer)}
timer = setTimeout(function(){
fn.apply(context, args)
}, delay)
}
}
- 防抖如果需要立即执行
function debounce(fn, delay, immediate){
let timer
return function(){
const context = this
const args = arguments
if(timer){clearTimeout(timer)}
if(immediate){
let callNow = !timer
// n 秒后触发,重新计时
timer = setTimeout(function(){
timer = null
}, delay)
if(callNow){fn.apply(context, args)}
} else {
timer = setTimeout(function(){
fn.apply(context, args)
}, delay)
}
}
}
应用场景
节流
- 滚动加载,scroll
防抖
- 搜索框搜索输入。只需用户输入完,再发送请求
- 窗口大小 resize