js anti-shake, throttling

To implement _sendBusinessCircle()the function only once in 1 second, according to the last calculation time, you can use the function in JavaScript setTimeoutcombined with anti-shake (debounce) technology

export default {
  name: "WriteComment",
  data() {
    return {
      debounceTimer: null, // 添加一个用于防抖的定时器
    };
  },
  methods: {
    _sendBusinessCircle() {
      // 这里是您的 _sendBusinessCircle 函数的原始代码
    },
    debounceSendBusinessCircle() {
      clearTimeout(this.debounceTimer); // 清除之前的定时器(如果有)
      this.debounceTimer = setTimeout(() => {
        this._sendBusinessCircle();
      }, 1000); // 设置新的定时器,在 1 秒后执行 _sendBusinessCircle()
    },
  },
};

To start counting the time on the first click and ensure that the function is only executed once in the next 1 second _sendBusinessCircle(), you can use the throttle technique. Here is a throttle using

export default {
  name: "WriteComment",
  data() {
    return {
      lastExecutionTime: 0, // 添加一个用于节流的变量,存储上次执行的时间
    };
  },
  methods: {
    _sendBusinessCircle() {
      // 这里是您的 _sendBusinessCircle 函数的原始代码
    },
    throttleSendBusinessCircle() {
      const currentTime = new Date().getTime();
      if (currentTime - this.lastExecutionTime > 1000) { // 检查距离上次执行是否已经过了 1 秒
        this._sendBusinessCircle();
        this.lastExecutionTime = currentTime; // 更新上次执行的时间
      }
    },
  },
};

Guess you like

Origin blog.csdn.net/weixin_44523517/article/details/130029723