美文网首页
debounce防抖函数

debounce防抖函数

作者: jack钱 | 来源:发表于2022-04-20 16:26 被阅读0次
/**
 * 普通防抖
 * @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)
});

相关文章

  • [JavaScript] 函数节流(throttle)和函数防抖

    js 的函数节流(throttle)和函数防抖(debounce)概述 函数防抖(debounce) 一个事件频繁...

  • javascript 函数防抖、函数节流

    函数防抖(debounce ) 函数节流

  • 函数的防抖与节流

    函数防抖(debounce) 防抖函数 debounce 指的是某个函数在某段时间内,无论触发了多少次回调,都只执...

  • js函数防抖与函数节流

    1.函数防抖(debounce) 函数防抖,debounce。其概念其实是从机械开关和继电器的“去弹跳”(debo...

  • 防抖与节流

    1. 防抖函数 1.1 防抖定义: 函数防抖(debounce):当持续触发事件时(例如mousemove),一定...

  • JS函数防抖

    JS 中的函数防抖 一、什么是函数防抖? 概念: 函数防抖(debounce), 就是指触发事件后,在 n 秒内函...

  • 防抖函数及其应用

    建议使用 lodash 插件里面的 debounce 函数来实现 1、防抖函数简单原理 2、防抖函数的应用

  • 函数节流与函数防抖

    函数节流与函数防抖的区别JS魔法堂:函数节流(throttle)与函数去抖(debounce)函数的防抖与节流 自...

  • 什么是throttle和debounce

    debounce 函数防抖_.debounce(func, delay, immediate); 第一次触发后,进...

  • JS笔试题

    JavaScript 笔试部分 实现防抖函数(debounce) 防抖函数原理:在事件被触发 n 秒后再执行回调,...

网友评论

      本文标题:debounce防抖函数

      本文链接:https://www.haomeiwen.com/subject/favvertx.html