防抖
function debounce(fn, delay = 500) { let timer = null return function() { if(timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(this, arguments) timer = null }, delay) }}
节流
function throttle(fn, delay = 200) { let timer = null return function() { if(timer) { return } timer = setTimeout(()=> { fn.apply(this, arguments) timer = null }, delay) }}
注:防抖和节流的写法其实差不多,只是当setTimeout存在时,防抖和节流执行的逻辑有差别。
防抖:触发高频事件时,在delay时间内函数最终只会执行一次,如果在delay时间内再次触发事件,则重新计算时间;节流:触发高频事件时,稀释函数执行的频率
//fn.apply(this, arguments)是为了方便调用时传参用。