2rever的前端小站

防抖和节流

Word count: 171 / Reading time: 1 min
2019/12/08 Share

debounce与trottle函数的适用场景有什么不同?

  1. 连续多次执行的事件只需要触发最后一次,就用debounce
  2. 如果只是需要降低事件处理函数的执行频率,则用throttle

简易实现 debounce

1
2
3
4
5
6
7
8
9
function debounce(f, duration) {
var timeoutId
return function(...args) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
f.call(this, ...args)
}, duration)
}
}

简易实现 throttle

1
2
3
4
5
6
7
8
9
10
function throttle(f, duration) {
var lastTime = 0
return function(...args) {
var now = Date.now()
if (now - lastTime > duration) {
f.call(this, ...args)
lastTime = now
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
function throttle(f, duration) {
var lastRunTime = -Infinity
var lastResult
return function(...args) {
var now = Date.now()
if (now - lastRunTime > duration) {
lastResult = f.call(this, ...args)
lastRunTime = now
}
return lastResult
}
}

`

CATALOG
  1. 1. debounce与trottle函数的适用场景有什么不同?
  • 简易实现 debounce
  • 简易实现 throttle