Skip to main content

防抖和节流

CREATE: 2022-03-11 22:14:09

题目:防抖和节流 ( 中等😄 )

请利用Ts | Js,实现防抖和节流函数

分析

项目内容
防抖调用函数触发冷却时间,如果在delay时间内再次被调用,则重新计时冷却时间
节流固定时间被调用
区别防抖是贪婪的,如果在delay时间内反复调用,那么该函数永远不会执行
而节流是开发的,固定时间调用,不管是否在delay时间内调用

题解

以下实现是伊拉克战损版,实际生产中建议用 lodash 库,lodash的防抖函数写得很复杂,边界情况处理到位,还具有 cancel、flush和pending方法,控制函数的执行,详见 debounce

防抖

function debounce(fn: () => void, wait = 50, immediate = true) {
let timer = null

return (...args) => {
if (timer) {
clearTimeout(timer)
}
if (!timer && immediate) {
fn.apply(null, args)
}

timer = setTimeout(() => {
// !immediate && fn.apply(null, args)
fn.apply(null, args)
}, wait)
}
}

使用

function main() {
const fn = debounce(() => {
console.log('[13232323233]:')
})

let counter = 0
const timer = setInterval(() => {
if (counter > 10) {
clearInterval(timer)
}

++counter
fn()
}, 100)
}

main()

节流

function throttle(fn: () => void, wait = 50) {
// let lastTime: number = -Infinity
let lastTime: number = 0

return function (...args) {
const curr = new Date().getTime()

if (curr - lastTime >= wait) {
// apply null said that it is window object
// fn.apply(null, args)

// It's better to pass `this` here
// If you use the arrow function outside, it doesn't work here
fn.apply(this, args)
lastTime = curr
}
}
}

使用

function main() {
const that = this

// const throttled = throttle(() => {
// console.log('[equal]:', that === this)
// console.log('[1秒打印一次]:')
// }, 1000)
const throttled = throttle(function () {
console.log('[this]:', this)
console.log('[equal]:', that === this)
console.log('[1秒打印一次]:')
}, 1000)

setInterval(() => {
throttled()
}, 100)
}

main()