zoukankan      html  css  js  c++  java
  • 防抖和节流

    /**
     * 防抖
     *
     * @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);
    

      

  • 相关阅读:
    SQL 语句添加约束
    sql server 的表进行设计后保存不了,一下方法可以解决
    约束的类型大全Sql server视图创建
    Python求和
    冒泡排序
    Python连接M有SQL,新增操作
    Python连接MYSQL,并做查询操作
    Python实现水仙花数
    测试工程师的一些面试题目(python)
    转:用Python解答百度测试开发算法面试题
  • 原文地址:https://www.cnblogs.com/tipsydr/p/15233331.html
Copyright © 2011-2022 走看看