防抖(debounce):
防抖用于确保一个函数在指定时间内只触发一次。它在短时间内屡次触发同一个事件时,会勾销之前的触发,直到最初一次触发后的肯定工夫距离内没有新的触发才执行函数。
常见的利用场景包含:
- 输入框实时搜寻:当用户在输入框中输出时,能够应用防抖技术提早执行搜寻查问,缩小不必要的查问和服务器压力。
- 窗口大小调整:当用户调整浏览器窗口大小时,能够应用防抖技术防止在调整过程中频繁地从新计算布局。
- 表单验证:当用户在表单输出时,能够应用防抖技术在用户进行输出一段时间后再执行验证,缩小验证的次数。
/** * @description 防抖函数 * @param {function} fn * @param {number} delay * @param {boolean} immediate * @returns {function} */ export function debounce<t extends (...args: any[]) => any>( fn: t, delay: number, immediate: boolean = false ): t & { cancel(): void } { let timerid: returntype<typeof settimeout> | null = null; // 存储定时器 // 定义一个cancel办法,用于勾销防抖 const cancel = (): void => { if (timerid) { cleartimeout(timerid); timerid = null; } }; const debounced = function ( this: thisparametertype<t>, ...args: parameters<t> ): void { const context = this; if (timerid) { cancel(); } if (immediate) { // 如果 immediate 为 true 并且没有正在期待执行的定时器,立刻执行指标函数 if (!timerid) { fn.apply(context, args); } // 设置定时器,在延迟时间后将 timeoutid 设为 null timerid = settimeout(() => { timerid = null; }, delay); } else { // 设置定时器,在延迟时间后执行指标函数 timerid = settimeout(() => { fn.apply(context, args); }, delay); } }; // 将 cancel 办法附加到 debounced 函数上 (debounced as any).cancel = cancel; return debounced as t & { cancel(): void }; }
节流(throttle):
节流用于确保一个函数在肯定工夫内最多只触发一次。它会在触发事件期间以固定的工夫距离执行函数,而不论事件触发得多频繁。
常见的利用场景包含:
- 滚动事件监听:例如监听页面滚动到底部加载更多数据时,能够应用节流技术缩小查看滚动地位的频率,进步性能。
- 鼠标挪动事件:例如实现一个拖拽性能,能够应用节流技术缩小鼠标挪动事件的解决频率。
- 动画成果:当实现一个基于工夫的动画成果时,能够应用节流技术限度动画帧率,升高计算开销。
总之,防抖和节流技术都能够在不同场景下进步利用性能。防抖实用于屡次触发只需执行一次的状况,而节流实用于限度间断触发事件的执行频率。
/** * 节流函数 * @param func 要进行节流的指标函数 * @param delay 节流的工夫距离(毫秒) * @returns 返回一个通过节流解决的函数 */ export function throttle<t extends (...args: any[]) => any>( fn: t, delay: number ): t { let lastcall: number | null = null; // 上一次调用的工夫戳 return function ( this: thisparametertype<t>, ...args: parameters<t> ): returntype<t> | void { const now = date.now(); //以后工夫戳 // 如果之前没有调用过,或者工夫距离超过了设定的值,执行指标函数 if (!lastcall || now - lastcall >= delay) { lastcall = now; return fn.apply(this, args); } } as t; }
以上就是typescript防抖节流实现示例详解的详细内容,更多关于typescript防抖节流的资料请关注代码网其它相关文章!
发表评论