一、手写防抖和节流
何为防抖(debonce):
防抖的意思是,n 秒内只能执行一次。如果 n 秒内事件被重复触发,则重新计时。
何为节流:(throttle)
节流的意思是, 单位时间内,只能触发一次。节流会稀释触发的频率。
通俗的说: 防抖就是 n 秒后执行函数。如果被重复触发,则重新计时。类似于回城效果。 节流是不管 n 秒内有没有被重新触发,都只能执行一次。类似于CD。
防抖
:::info
防抖 (debounce) : 利用定时器实现,n 秒后执行。
节流 (throttle) : 利用时间戳时间,n 秒内只执行一次。
:::
// 防抖function debounce(fn, wait) {let timer = nullreturn function() {// 通过闭包获取 fn 的参数: fn(a, b) -> debounce(fn, 1000)(a, b)const context = this,args = arguments// 因为用了定时器,所以记得清除定时器if (timer) {clearTimeout(timer)timer = null}timer = setTimeout(fn.apply(context, args), wait)}}
节流
// 节流function throttle(fn, delay) {let currTime= Date.now()return function() {const context = this,args = argumentsendTime = Date.now()// n 秒内只执行一次,所以通过 时间戳来判断if (endTime - currTime >= delay) {currentTime = Date.now()return fn.apply(context, args)}}}
