0%

防抖 && 节流

防抖节流

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
31
/**
* 防抖:
* 频繁触发事件,设定一个时间间隔,当 相邻两次事件 的触发时间间隔 小于设定的时间,则重新设定,大于则触发
*
* 节流
* 频繁触发事件,每隔一段时间触发一次
*/

const debounce = function (fn, wait = 1000) {
let timer = null
return function () {
if (timer) clearTimeout(timer)
const _this = this
const _args = [...arguments]
timer = setTimeout(() => {
fn.apply(_this, _args)
}, wait);
}
}

const throttle = function (fn, wait) {
let timer = null
return function (...args) {
if (timer) return
timer = setTimeout(() => {
fn.apply(this, args)
clearTimeout(timer)
timer = null
}, wait);
}
}

防抖 - 鼠标移动位置捕捉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const debounce = function (fun, delay) {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fun.apply(this, args)
}, delay);
}
}
const handle = debounce(e =>
console.log('x: ' + e.pageX, ' , y: ' + e.pageY)
, 500)

window.addEventListener('mousemove', debounce(e => console.log(e.pageX), 500))
-------------本文结束感谢您的阅读-------------