欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > 节流、防抖函数(TypeScript)

节流、防抖函数(TypeScript)

2024/10/24 19:18:15 来源:https://blog.csdn.net/weixin_50368372/article/details/140869975  浏览:    关键词:节流、防抖函数(TypeScript)

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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com