• 防抖和节流


    /**
     * 防抖
     *
     * @param {*} f
     * @param {*} wait
     * @return {*} 
     */
    function debounce(f, wait) {
      let timer = null;
      return (...args) => {
        if(timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          f(...args);
        }, wait);
      }
    }
    
    /**
     * 节流 非首次执行
     *
     * @param {*} f
     * @param {*} wait
     * @return {*} 
     */
    function throttle(f, wait) {
      let timer = null;
      return (...args) => {
        if(timer) {
          return
        }
        timer = setTimeout(() => {
          f(...args);
          timer = null;
        }, wait);
      }
    }
    
    /**
     * 节流 首次执行
     *
     * @param {*} f
     * @param {*} wait
     * @return {*} 
     */
    function throttle(f, wait) {
      let last = 0;
      return (...args) => {
        const now = Date.now();
        if(now - last >= wait) {
          f(...args);
          last = now;
        }
      }
    }
    
    /**
     * 节流 两者结合
     *
     * @param {*} f
     * @param {*} wait
     * @return {*} 
     */
    function throttle(f, wait) {
      let last = 0;
      let timer = null;
      return (...args) => {
        const now = Date.now();
        const remaining = wait - (now - last);
    
        clearTimeout(timer)
    
        if(remaining <= 0) {
          f(...args);
          last = Date.now();
        }
        else {
          if(timer) return;
          timer = setInterval(() => {
            f(...args);
            last = Date.now();
          }, remaining);
    
        }
      }
    }
    
    function sayHellow() {
      console.log('hellow');
    }
    
    // const debounceSayHellow = debounce(sayHellow, 2000);
    
    // debounceSayHellow();
    // debounceSayHellow();
    // debounceSayHellow();
    // debounceSayHellow();
    // debounceSayHellow();
    // debounceSayHellow();
    
    const throttleSayHellow = throttle(sayHellow, 2000);
    
    setInterval(() => {
      throttleSayHellow();
    }, 500);
    

      

  • 相关阅读:
    npropress进度条插件的使用
    让img图片像背景一样显示
    vue-cli3配置多页面入口
    7中漂亮的纯css字体
    速查手册
    推荐系统架构
    leetcode 172. 阶乘后的零
    C++ string和int互相转换
    特征分解
    线性代数基础
  • 原文地址:https://www.cnblogs.com/tipsydr/p/15233331.html
Copyright © 2020-2023  润新知