# 防抖 debounce
- 防抖:规定时间内只执行一次,重复触发会不停刷新执行函数的等待时间
function debounce(fn, wait, immediate){
let timer;
return function() {
if(immediate){
fn.apply(this, arguments)
}
if(timer){
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
}, wait);
}
}
function realFunc(){
console.log("Success")
}
// 采用防抖动
window.addEventListener('scroll', debounce(realFunc, 500))
// 未采用防抖动
window.addEventListener('scroll', realFunc)
# 节流 throttle
- 节流:规定时间内只执行一次,重复触发会被屏蔽,不会刷新等待时间
function throttle(fn, wait){
let prev = new Date()
return function(){
const now = new Date()
if(now - prev > wait){
fn.apply(this, arguments);
prev = new Date()
}
}
}
function throttle(fn, wait){
let canRun = true
return function(){
if(!canRun){
return
}
canRun = false
fn.apply(this, arguments)
setTimeout(() => {
canRun = true
}, wait);
}
}
const throttle = function(fn, delay, isDebounce){
let timer, lastCall = 0
return function(...args){
if(isDebounce){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(() => {
fn(...args)
}, delay);
}else{
const now = new Date()
if(now - lastCall < delay){
return
}
lastCall = now
fn(...args)
}
}
}
← call和apply的手写实现 事件循环 →