HarmonyOS 鸿蒙Next中防抖与节流的优雅通用版实现
HarmonyOS 鸿蒙Next中防抖与节流的优雅通用版实现
/**
- 防抖 高阶函数
- 返回的函数不需要传参,直接使用this访问外部数据即可
- @param fn 传入频繁触发的函数
- @param delay 延迟时间
- @returns */ export function debounce(fn: Function, delay: number = 300) { let timer: number = 0 return () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn() }, delay) } }
/**
-
节流 高阶函数
-
@param callBack
-
@param delay
-
@param immediately 是否立即执行
-
@returns */ export function throttle(callBack: Function, delay: number = 300, immediately: boolean = true) { let timer = 0 if (immediately) { return () => { if (Date.now() - timer >= delay) { callBack() timer = Date.now() } } } else { return () => { if (timer) { return }
timer = setTimeout(() => { callBack() timer = 0 }, delay) } } }
//入口页 import { debounce, throttle } from ‘…/common/utilrs’
@Entry @Component struct Index { a: string = ‘yujia’ dfn = debounce(() => { console.log(“点击了 防抖”, this.a) }, 600) tfn = throttle(() => { console.log(“点击了 节流”, this.a) }, 3000, true)
build() { Column() { Image($r(‘app.media.startIcon’)) .width(300) .height(300) .onClick(this.tfn) } } }
更多关于HarmonyOS 鸿蒙Next中防抖与节流的优雅通用版实现的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS 鸿蒙Next中防抖与节流的优雅通用版实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,防抖(Debounce)和节流(Throttle)可以通过@ohos.worker
模块实现。以下是一个优雅的通用版实现:
// 防抖函数
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// 节流函数
function throttle(func, wait) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= wait) {
func.apply(this, args);
lastTime = now;
}
};
}
// 使用示例
const debouncedFn = debounce(() => console.log('Debounced!'), 300);
const throttledFn = throttle(() => console.log('Throttled!'), 300);
通过debounce
和throttle
函数,可以有效控制事件触发的频率,提升应用性能。