如何停止随机超时功能



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

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" />

最新更新