javascript - 如何随机停止超时功能

标签 javascript vue.js

我有一个每 90 毫秒添加 0.015 的值,并且它会无限增加,所以现在我希望它在单击按钮后随机停止。我写了代码,但似乎不起作用

data:{
 crashValue: 1,
},
methods:{
    crashFunction: function() {
      this.crashValue += 0.0150;
      this.startTimer();
    },
    startTimer () {
      let interval = 90
      if (this.crashValue > 2.15) {
        interval = 80
      }
      if (this.crashValue > 3.15) {
        interval = 70
      }
      if (this.crashValue > 4) {
        interval = 60
      }
      if (this.crashValue > 6.15) {
        interval = 55
      }
      if (this.crashValue > 8) {
        interval = 48
      }
      if (this.crashValue > 10) {
        interval = 35
      }
      if (this.crashValue > 15) {
        interval = 26
      }
      if (this.crashValue > 22) {
        interval = 16
      }
      this.tessst = setTimeout(this.crashFunction, interval);
    },
    randomStop(){
      let asd = Math.floor(Math.random() * 5000)
      console.log(asd)
      clearTimeout(() => this.startTimer(), asd)
    },
}
<button class="stopCrash" :disabled="disableCashOut" @click="cashOut(); randomStop()">Cash out</button>

最佳答案

clearTimeout 的文档清楚地表明唯一的参数是 setTimeout 提供的 ID。

如果你想停止你的“循环”,首先你需要传递正确的值,在你的例子中它是clearTimeout(this.tessst)

如果您希望在随机时间后触发 clearTimeout,那么您需要另一个 setTimeout...看,您可以运行下面的示例。

var count = 0;
var timerId = null;
function startTimer() {
  console.log(++count);
  timerId = setTimeout(startTimer, 1000);
}
function stopTimer() {
  var rnd = Math.floor(Math.random() * 5000);
  console.log("Stopping in " + (rnd / 1000) + " seconds");
  setTimeout(function() {
    clearTimeout(timerId);
    console.log("Stopped");
  }, rnd);
}
startTimer();
<input type="button" onclick="stopTimer();" value="Stop" />

关于javascript - 如何随机停止超时功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59930120/

相关文章:

javascript - 如何根据要素图层的字段值更改 infoTemplate 内容

javascript - 如何使用rabbitmq在nodejs中设计一个任务调度程序,使其在跨多个进程时不会运行相同的任务?

Javascript 类丢失了对 'this' 的引用(使用 babel)

javascript - Vue react 性 : Computed changes data but then is not reacting to it

javascript - 如何替换Vuejs路由器中的一个参数

laravel - 仅在需要时使用 Echo 在 Laravel-Vue js 应用程序中建立与 Pusher 的连接

typescript - 无法摆脱 VS Code 中的此 "The 2 extension(s) below, in workspace recommendations have issues"消息

javascript - vuex 突变取代了整个状态

css - 如何更改 Vuetify 中文本字段的宽度和高度?

javascript - 使用 Jest 测试 node-cron 作业功能