throttle/index.js

import cavar_type from "../cavar_type";

/**
 * 功能:节流功能函数,对特殊事件进行节流操作,按照规定时间执行callback函数
* @param {function} callback - 执行函数
* @param {number|string} [dayNum] - default is 300 延时时间  如果字符串isNaN后结果为true把dayNum重置为300
* @returns {undefined} - undefined
 */
function throttle(callback, dayNum = 300) {
    let task_time = 0;
    function execute_function(execute_dayNum) {
      if (new Date().getTime() - task_time >= execute_dayNum) {
        callback();
        task_time = new Date().getTime();
      }
    }
    if (cavar_type(callback) === "function") {
      return function () {
        if (cavar_type(dayNum) === "number") {
          execute_function(dayNum);
        } else if (cavar_type(dayNum) === "string") {
          if (isNaN(dayNum)) {
            execute_function(300);
            console.error(
              new Error(
                "throttle: second parameter is not NAN you is sb, but dayNum become 300"
              )
            );
          } else {
            execute_function(dayNum);
          }
        }
      };
    } else {
      console.error(
        new Error("throttle: first parameter is not function you is sb")
      );
      // 避免没有必要的报错
      return () => {};
    }
  }
  export default throttle;