1、节流函数
节流(throttling)函数是一种在特定时间内只允许某个函数执行一次的技术。它可以用于限制函数执行的频率,例如在滚动、窗口调整大小、鼠标移动等高频事件中使用,避免函数被过多调用,导致性能问题。
定时器实现节流
/**
* @param func { T } => 节流的函数
* @param limit { number } => 节流时间(毫秒)
*/
function throttle<T extends (...args: any[]) => void>(func: T, limit: number): T {
let inThrottle: boolean;
return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
} as T;
}
时间戳实现节流
/**
* @param func { T } => 节流的函数
* @param limit { number } => 节流时间(毫秒)
*/
function throttle<T extends (...args: any[]) => void>(func: T, limit: number): T {
let lastFunc: ReturnType<typeof setTimeout>;
let lastRan: number;
return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
} as T;
}
使用方法
// 需节流的函数
function func () {
console.log("123123123......")
}
window.addEventListener('scroll', throttle(func, 1000));
2、防抖函数
防抖(debounce)函数是一种在事件触发后,等待一段时间,如果在等待期间事件再次被触发,则重新开始计时,直到等待时间结束才执行函数。这可以避免在短时间内多次触发同一个事件时多次执行相应的处理函数。
/**
* @param func { T } => 防抖的函数
* @param wait { number } => 防抖时间(毫秒)
*/
function debounce<T extends (...args: any[]) => any>(func: T, wait: number): T {
let timeout: ReturnType<typeof setTimeout>;
return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
} as T;
}
使用方法
// 防抖函数
const func = debounce(() => {
console.log("123123123......")
}, 1000)