节流
节流相当于游戏里的冷却时间,执行一次后,n秒内不能执行第二次
function throttle(fn, delay){let canUse = truereturn function(){if(canUse){fn.apply(this, arguments)canUse = falsesetTimeout(()=>canUse = true, delay)}}}const throttled = throttle(()=>console.log('hi'))throttled()throttled() // 不会执行
防抖
对于频繁触发的事件,n秒后才执行,如果上一次触发的事件还未执行,这次又触发了,则以这次的时间为准,n秒后执行
function debounce(fn, delay){let timerId = nullreturn function(){const context = thisif(timerId){window.clearTimeout(timerId)}timerId = setTimeout(()=>{fn.apply(context, arguments)timerId = null}, delay)}}const debounced = debounce(()=>console.log('hi'))debounced() // 不会执行debounced()
函数节流和函数防抖都是优化高频率执行js代码的一种手段,提升用户体验,减少资源浪费。
