防抖和节流的概念以及实现
概念
使用监听滚动,或者鼠标移动这样的频繁触发的事件,可能会导致页面卡顿或者假死,所以针对这种高频触发的事件的问题,有两种解决方案,节流和防抖
防抖:触发高频事件以后,会延迟一段时间以后再执行,如果这个期间又触发了该事件,就会重新计算时间
节流:当高频事件触发的时候,n秒只执行一次
实现
防抖实现思想:设定一个高频事件触发的开始时间,设置每次过一段时间后就把this重新绑定,也就是重新绑定这个函数,如果在n秒内就清除计时器,重新计算触发开始时间,反之也重新绑定函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| window.onmousemove = debounce(fun, 100) function debounce(callback, time) { let timeStamp = 0 let timer = null let content, args
let run = () => { timer = setTimeout(() => { callback.apply(context, args) }, time) }
return function () { context = this args = arguments let now = (new Date()).getTime()
if(now - timeStamp < time) { clearTimeout(timer) run() } else { run() } timeStamp = now } }
function fun() { console.log('哈哈哈') }
|
节流的实现就是,当触发事件的时候,设置一个定时器,如果在周期内再次触发事件,就忽略,等到时间执行完函数,就把定时器删了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| function fun() { console.log('哈哈哈') }
function throttle(callback, delay) { let timer = null let context, args
let run = () => { timer = setTimeout(() => { fun.apply(context, args) clearTimeout(timer) timer = null }, delay) }
return function() { context = this args = arguments if(!timer) { run() } } }
window.onmousemove = throttle(fun, 500)
|
其他扩展
匿名函数作用:避免污染全局变量
apply和call改变函数内部的指向,区别是参数数量不一样