首页 > 解决方案 > 两个 setTimeout 函数不能单独工作

问题描述

我的值每 90 毫秒添加 0.0150,当值变为 2.15 时,每 80 毫秒添加 0.0150,但我想做其中两个函数,我的意思是在 3.15 之后,我希望每 70 毫秒添加 0.0150,等等我写了这个功能但没有任何解决方案?

  data:{
    crashValue: 1
  },
  mounted(){
    this.startTimer();
  },
  methods:{
    crashFunction: function() {
      this.crashValue += 0.0150;
      this.startTimer();
    },
    startTimer(){
      setTimeout(this.crashFunction, this.crashValue > 2.15 ? 80 : 90);
      setTimeout(this.crashFunction, this.crashValue > 3.15 ? 70 : 80); // When I add this it value goes up really really fast
    }
  }
          <h2 class="crashNumber">{{ crashValue.toFixed(2) }}x</h2><br />

标签: javascriptvue.js

解决方案


你的意思是这样的吗?

startTimer () {
  let interval = 90

  if (this.crashValue > 2.15) {
    interval = 80
  }

  if (this.crashValue > 3.15) {
    interval = 70
  }

  setTimeout(this.crashFunction, interval);
}

在您的代码中,您正在创建两个同时运行的计时器。每次其中一个计时器触发时,它都会创建另外两个计时器,从而导致正在运行的计时器数量呈指数增长。

如果我理解正确,那么您只需要一个计时器和一些合适的逻辑来确定当前间隔。


推荐阅读