防抖节流应用场景?
按照需求来确定是用防抖还是节流:
tips: 在连续频繁操作的时间区域内,要能执行函数的情况用节流。
- 监听浏览器resize事件;
- 文本编辑器实时保存;
- 输入框的模糊查询功能;
…
防抖函数
防抖的原理是什么?
防抖的原理就是:不管怎么触发事件,但是一定在事件触发 n 秒后才执行,如果一个事件触发的 n 秒内又触发了这个事件,那就以新事件的时间为准,n 秒后才执行,总之就是要等触发完事件 n 秒内不再触发事件才执行。
实现一个防抖函数?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const debounce = (fn, delay) => { let timer = null
return function () { let args = arguments
if (timer) clearTimeout(timer) timer = setTimeout(() => { fn.apply(this, args) }, delay) } }
|
节流函数
节流的原理是什么?
节流的原理是:一个函数执行一次后,只有大于设定的执行周期,才会执行第二次。也就是说:在规定的时间内,只让函数触发的第一次生效,后面的不生效。
实现一个节流函数?
1.使用定时器
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
| const throttle = (fn, delay) => { let timer = null
return function () { let args = arguments
if (!timer) { timer = setTimeout(() => {
timer = null fn.apply(this, args) }, delay) } } }
|
2.使用时间戳
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function throttle_2(fn, delay) { let previous = 0; return function () { let args = arguments const nowTime = Date.now()
if (nowTime - previous > delay) { fn.apply(this, args) previous = nowTime } } }
|