手写防抖与节流函数
我们经常会绑定一些持续触发的事件,比如resize、scroll、mousemove等等,如果事件调用无限制,会加重浏览器负担,导致用户体验差,我们可以使用debounce(防抖)和throttle(节流)的方式来减少频繁的调用,同时也不会影响实际的效果。
防抖的概念
触发事件后n秒后才执行函数,如果在n秒内触发了事件,则会重新计算函数执行时间
防抖函数可以分为立即执行,和非立即执行两个版本
非立即执行版本
1
2
3
4
5
6
7
8
9
10
11function debounce(fn, wait) {
let timer = null
return function () {
const context = this
const args = arguments
timer && clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(context, args)
}, wait)
}
}此函数一开始不会马上执行,而是等到用户操作结束之后等待wait秒后才执行,如果在wait之内用户又触发了事件,则会重新计算
立即执行版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14function debounce(fn, wait) {
let timer = null
return function () {
const args = arguments
const now = !timer
timer && clearTimeout(timer)
timer = setTimeout(() => {
timer = null
}, wait)
if (now) {
fn.apply(this, args)
}
}
}立即执行就是触发事件后马上先执行一次,直到用户停止执行事件等待wait秒后再执行一次
我们可以将两种版本合并成一种
1 |
|
节流的概念
连续触发事件但在n秒内只执行一次函数
对于节流有时间戳和定时器两种版本
- 时间戳版本在持续触发事件的过程中,函数会立即执行,用户在wait秒内不管执行多少次事件,都会等待wait秒后再执行。
1
2
3
4
5
6
7
8
9
10
11
12function throttle(fn, wait) {
var prev = 0
return function () {
let now = Date.now()
let context = this
let args = arguments
if (now - prev > wait) {
fn.apply(context, args)
prev = now
}
}
} - 定时器版本在触发事件的过程中,不会立即执行,并且每wait秒执行一次,在停止触发事件后还会再执行一次。
1
2
3
4
5
6
7
8
9
10
11
12
13function throttle(fn, wait) {
var timer = null
return function () {
const context = this
const args = arguments
if (!timer) {
timer = setTimeout(() => {
timer = null
fn.apply(context, args)
}, wait)
}
}
}
时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候。
将两种方式合并
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!