- 防抖debounce(事件被触发n秒后执行回调函数, 如果在这n秒内又被触发, 则重新计时)
//debounce antvis/utils
function debounce(func: Function, wait?: number, immediate?: boolean) {
let timeout;
return function () {
const context = this,
args = arguments;
const later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
export default debounce;
- 节流
//throttle
let last = 0;
function throttle(fn, gapTime, ...arg) {
let nowTime = Date.now();
if(nowTime - last > gapTime) {
fn.apply(this, ...arg);
last = nowTime;
}
}
// throttle by requestanimation
export function throttleByRaf(cb: (...args: any[]) => void) {
let timer = 0;
const throttle = (...args: any[]): void => {
if (timer) {
cancelAnimationFrame(timer);
}
timer = requestAnimationFrame(() => {
cb(...args);
timer = 0;
});
};
throttle.cancel = () => {
cancelAnimationFrame(timer);
timer = 0;
};
return throttle;
}
On This Page