函數(shù)防抖:在事件被觸發(fā)n秒后再執(zhí)行回調(diào),如果在這n秒內(nèi)又被觸發(fā),則重新計時。這個我經(jīng)常用到
/**
* 函數(shù)防抖
* fun 需要延時執(zhí)行的函數(shù)
* delayTime 延時時間
* **/
export function debounce (func, delay) {
let timer
return function (...args) {
console.log('進來了!')
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}
函數(shù)節(jié)流:規(guī)定一個單位時間,在這個單位時間內(nèi),只能有一次觸發(fā)事件的回調(diào)函數(shù)執(zhí)行,如果在同一個單位時間內(nèi)某事件被觸發(fā)多次,只有一次能生效
/**
* 函數(shù)防抖
* fun 需要延時執(zhí)行的函數(shù)
* delayTime 延時時間
* **/
export function throttle(fun, gapTime) {
let _lastTime = null;
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fun();
_lastTime = _nowTime
}
}
}
let fn = ()=>{
console.log('boom')
}
setInterval(throttle(fn,1000),10)