一。函数防抖:基本思想是指,某些代码不可以在没有间断的情况连续重复执行。第一次调用函数, 创建一个定时器,在指定的时间间隔之后运行代码。当第二次调用该函数时,它会清除前一次的定时器 并设置另一个。如果前一个定时器已经执行过了,这个操作就没有任何意义。然而,如果前一个定时器 尚未执行,其实就是将其替换为一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后才 执行。常用于 onresize 事件。
function debounce (fn, delay = 100, context) {
let Timer = 0
return function () {
clearTimeout(Timer)
Timer = setTimeout(() => {
fn.call(context)
}, delay)
}
}
测试代码:
function test () {
console.log('我是测试代码!')
}
let variable = debounce(test)
for (let i = 0; i < 10000; i++) {
variable()
}
输出:我是测试代码!
最终发现通过调用10000次改函数结果只触发了一次。并且触发的时间是执行完后延迟 100ms才输出的。首次不会触发
二。函数节流:指在指定的时间内,只触发一次。
function throttle (fn, delay = 100, context) {
let last = 0
return function () {
let now = new Date().valueOf()
if (now - last > delay || !last) {
last = now
fn.call(context)
}
}
}
function test () {
console.log('我是测试代码!')
}
let variable = throttle(test)
for (let i = 0; i < 10000; i++) {
variable()
}
输出:我是测试代码!
先立即输出。缺陷最后一次的操作并不能保证一定触发。
三。组合模式。
function compose (fn, delay = 100, context) {
let Timer = 0,
last = 0
return function () {
let now = new Date().valueOf()
if (now - last > delay || !last) {
last = now
fn.call(context)
}
clearTimeout(Timer)
Timer = setTimeout(() => {
fn.call(context)
}, delay)
}
}
首次和最后一次的操作都会触发。