anti_shake/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 anti_shake(callback, dayNum = 300) {
    let set_out_id;
    function execute_function(execute_dayNum) {
      set_out_id = setTimeout(() => {
        callback();
      }, execute_dayNum);
    }
    if (cavar_type(callback) === "function") {
      return function () {
        clearTimeout(set_out_id);
        if (cavar_type(dayNum) === "number") {
          execute_function(dayNum);
        } else if (cavar_type(dayNum) === "string") {
          if (isNaN(dayNum)) {
            execute_function(300);
            console.error(
              new Error(
                "anti_shake: second parameter is not NAN you is sb, but dayNum become 300"
              )
            );
          } else {
            execute_function(dayNum);
          }
        }
      };
    } else {
      console.error(
        new Error("anti_shake: first parameter is not function you is sb")
      );
      // 避免没有必要的报错
      return () => {};
    }
  }
  export default anti_shake;