防抖节流函数
小于 1 分钟
防抖节流函数
防抖节流函数主要用于减少函数不必要的重复调用,可以达到优化性能的效果。
防抖函数
/*
* File Created: Wednesday, 15th March 2023 5:29:32 pm
* Author: hotsuitor (hotsuitor@qq.com)
* -----
* Last Modified: Wednesday, 15th March 2023 5:34:06 pm
* Modified By: hotsuitor (hotsuitor@qq.com>)
*/
/**
* 防抖
* @param {*} fn 被包装的函数
* @param {*} delay 延迟时间 ms
* @returns
*/
function debounce(fn, delay) {
let timer = null
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
节流函数
/*
* File Created: Wednesday, 15th March 2023 5:29:43 pm
* Author: hotsuitor (hotsuitor@qq.com)
* -----
* Last Modified: Wednesday, 15th March 2023 5:34:19 pm
* Modified By: hotsuitor (hotsuitor@qq.com>)
*/
/** 简单版本 */
function throttle0(fn, wait=300) {
let lastTime = Date.now()
return (...args) => {
const now = Date.now()
if(now - lastTime > wait) {
fn.apply(this, args)
lastTime = now
}
}
}
function throttle(fn, wait = 300, imediate = false) {
let inThrottle = !immediate,
lastFn,
lastTime
return function () {
const context = this,
args = arguments
if (!inThrottle) {
fn.apply(context, args)
lastTime = Date.now()
inThrottle = true
} else {
clearTimeout(lastFn)
lastFn = setTimeout(function () {
if (Date.now() - lastTime > wait) {
fn.apply(context, args)
lastTime = Date.now()
}
}, Math.max(wait - (Date.now() - lastTime), 0))
}
}
}
// Example
window.addEventListener(
'resize',
throttle(function(evt) {
console.log(window.innerWidth);
console.log(window.innerHeight);
}, 250)
); // Will log the window dimensions at most every 250ms