debounce防抖函数

2022-04-20  本文已影响0人  jack钱
/**
 * 普通防抖
 * @param func 防抖执行函数
 * @param wait 防抖间隔,默认0.5s
 * @returns function
 */
const debounce = function (func: any, wait = 500) {
    let timeout: any;
    return function (...event: any[]) { //...运算符可以传递多个参数
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            func.call(func, ...event)
        }, wait)
    }
}

/**
 * 返回promise的防抖
 * @param inner 防抖执行函数
 * @param ms 防抖间隔,默认0.5s
 * @returns function
 */
function asyncDebounce(inner: any, ms = 500) {
    let timer: any = null;
    let resolves: any = [];

    return function (...args: any[]) {
        // Run the function after a certain amount of time
        clearTimeout(timer);
        timer = setTimeout(() => {
            // Get the result of the inner function,then apply it to the resolve function of
            // each promise that has been created since the last time the inner function was run
            let result = inner(...args);
            resolves.forEach((r: any) => r(result));
            resolves = [];
        }, ms);

        return new Promise<any>(r => resolves.push(r));
    };
}
export {
    debounce,
    asyncDebounce
};
使用的时候用debounce函数将原函数包裹起来即可
// 返回promise的防抖
const getDictionary = asyncDebounce((typeKey: string) => {
  return new Promise<RequestOptionsType[]>((resolve, reject) => {
    if (!typeKey) {
      resolve([]);
      return;
    }
    queryListByTypeKey({ typeKey }).then(res => {
      resolve(res.data.map((item: any) => ({ label: item.name, value: item.value })));
    });
  });
});

// 普通防抖
const hangleChange = debounce(function(e){
  console.log(this.value)
});
上一篇 下一篇

猜你喜欢

热点阅读