节流&防抖
一、防抖 debounce(频繁操作最后触发,避免频繁触发)
场景
1. 监听一个输入框,内容发生变化触发change事件,当我们在输入或者删除时会频繁触发change事件,中间这些触发时没必要的,只要当我们停止改变时触发一次change就可以
2. 监听滚动条,滚动条滚动触发scroll事件,当我们滚动时会频繁触发scroll事件,中间这些触发没必要,只要当我们停止滚动时触发一次scroll就可以
代码封装
function debounce(fn, delay = 500) { let timer = null return function () { const _this = this let args = arguments if (timer) { // 再次触发,如果原来有未执行的定时器,则销毁原来的,然后重新创建一个 // 如果过了delay事件后,没有再触发就会执行定时器回调函数 clearTimeout(timer) } timer = setTimeout(() => { fn.apply(_this, args) timer = null }, delay) } }
使用demo
window.onscroll = debounce(() => { console.log('scroll') }, 1000)
二、节流 throttle(频繁操作,保持一定频率触发,即一定时间内只能触发一次)
场景
1. 拖拽实现,需要监听dragmove事件,随时获取拖拽元素位置然后改变元素位置,但是这些事件触发频率很高,1秒可能触发几十次,几百次,如果处理函数中还涉及dom操作会严重浪费计算机资源,降低性能,甚至造成卡顿。
2. 用户点击按钮触发ajax请求,如果用户快速点击就会频繁发出大量每必要的重复请求,占用网络资源。
代码封装
function throttle (fn, ms = 100) { let timer = null return function () { const _this = this let args = arguments // 定时器存在就不再创建新的定时器 if (!timer) { timer = setTimeout(function () { fn.apply(_this, args) timer = null }, ms) } } }
使用demo
document.onmousemove = throttle(() => { console.log('throttle') }, 500)
------------smile