返回专题

专题 2018

防抖节流

节流 相关笔记

JavaScript面试题
本文目录2
  1. 节流
  2. 防抖

节流

  • 简单的节流

    JavaScript
    // 函数节流,在高频率执行时,如果没有传入第二个参数则每300ms执行一次callback
    const throttle = (fn, timeout = 3000) => {
      let canDo = true;
      return (...args) => {
        if (canDo) {
          canDo = false;
          setTimeout(() => {
            canDo = true;
            fn.call(this, ...args);
          }, timeout);
        }
      };
    };
    
  • 定时或者达到调用次数的统一请求节流

    JavaScript
    // 函数节流,在高频率执行时,如果没有传入第二个参数则每300ms执行一次callback
    // 如果请求大于 5 个的话立即执行, 并且统一返回
    const throttleWithCount = (fn, timeout = 500, count = 5) => {
      let timer = null;
      let argsArray = [];
    
      const doFn = () => {
        clearTimeout(timer);
        const result = fn.call(this, ...argsArray);
        timer = null;
        argsArray = [];
        return result;
      };
    
      return (...args) => {
        return new Promise(resolve => {
          argsArray.push(args);
          // 已经超过 5 个请求的话, 清除定时器
          if (argsArray.length >= count) {
            console.log(`超过 ${count} 个请求`);
            resolve(doFn());
            return;
          }
    
          // 没有定时器的话, 等待过后统一请求
          if (!timer) {
            timer = setTimeout(() => {
              console.log(`超过 ${timeout} ms`);
              resolve(doFn());
            }, timeout);
            return;
          }
        });
      };
    };
    
    const testFunc = throttleWithCount((...args) => {
      console.log('testFunc', args);
      return Promise.resolve(args);
    });
    
    if (false) {
      [1, 2, 3, 4, 5].forEach(currentValue => {
        setTimeout(() => {
          testFunc(currentValue);
        }, 50 * currentValue);
      });
    } else {
      [1, 2, 3, 4, 5].forEach(currentValue => {
        setTimeout(() => {
          testFunc(currentValue);
        }, 200 * currentValue);
      });
    }
    

防抖

  • 简单的防抖

    JavaScript
    // 函数防抖,在高频率执行时,如果没有传入第二个参数则300ms内没有再次触发才执行callback
    const debounce = (fn, timeout = 3000) => {
      let timmer;
      return (...args) => {
        clearTimeout(timmer);
        timmer = setTimeout(() => {
          fn.call(this, ...args);
        }, timeout);
      };
    };
    
返回首页
上一篇微前端

Discussion

留言与讨论

想法、补充和不同意见都欢迎。