ClickUtil
export class ClickUtil {
private constructor() {
}
private static throttleTimeoutID: number; //節(jié)流timeoutID
private static flag: boolean = false; //節(jié)流flag,true=已經(jīng)進入執(zhí)行狀態(tài)了
private static debounceCacheID: number; //防抖timeoutID
/**
* 節(jié)流:在一定時間內(nèi)耘眨,只觸發(fā)一次
* @param func 要執(zhí)行的回調(diào)函數(shù)
* @param wait = 1500 延時的時間 毫秒
* @param immediate = true 是否立即執(zhí)行
*/
static throttle(func: () => void, wait: number = 1000, immediate: boolean = true) {
if (immediate) {
if (!ClickUtil.flag) {
ClickUtil.flag = true;
typeof func === 'function' && func();
ClickUtil.throttleTimeoutID = setTimeout(() => {
ClickUtil.flag = false;
clearTimeout(ClickUtil.throttleTimeoutID);
}, wait);
}
} else {
if (!ClickUtil.flag) {
ClickUtil.flag = true;
ClickUtil.throttleTimeoutID = setTimeout(() => {
ClickUtil.flag = false;
typeof func === 'function' && func();
clearTimeout(ClickUtil.throttleTimeoutID);
}, wait);
}
}
}
/**
* 防抖:一定時間內(nèi)昼榛,只有最后一次操作,再過wait毫秒后才執(zhí)行函數(shù)
* @param func 要執(zhí)行的函數(shù)
* @param wait 延時的時間
*/
static debounce(func: () => void, wait: number = 1000) {
if (ClickUtil.debounceCacheID) {
clearTimeout(ClickUtil.debounceCacheID);
}
let timeoutID = setTimeout(() => {
typeof func === 'function' && func();
clearTimeout(timeoutID);
}, wait);
ClickUtil.debounceCacheID = timeoutID;
}
}