javascript - 清除后重新开始间隔
问题描述
清除后如何重新启动Interval?我希望一个按钮每 11 秒可点击一次我禁用它,而计时器> 0 在它等于 0 之后按钮未被禁用,所以它是可点击setInterval()
的下降太快任何解决方案>
data:{
sTimer:11,
sDisabled:true,
asd:null
},
methods:{
testing(){
this.sTimer--;
if(this.sTimer == 0){
clearInterval(this.asd);
this.sTimer= 11;
this.sDisabled = false;
}else{
this.sDisabled = true;
}
},
specialAttack(){
setInterval(() => this.testing(), 1000)
}
},
created(){
this.asd = setInterval(() => this.testing(), 1000);
}
<button class="specialAttack" :disabled="sDisabled" @click="specialAttack(); testing()">Special Attack {{ sTimer }}</button>
解决方案
你在这里犯了几个错误,所以首先要实现这样的事情你应该使用setTimeout
而不是setInterval
因为间隔通常会在给定时间后重复,所以这可能是你点击你的被调用两次的可能原因之一按钮。然后您需要为此创建一个通用函数,然后在文档创建中调用它,而不是创建两个不同的间隔并分别调用它们。
所以尊重这些规则,你的最终代码应该是这样的:
HTML
<button class="specialAttack" :disabled="sDisabled" @click="specialAttack();">Special Attack {{ sTimer }}</button>
Javascript
data: () => {
return {
sTimer: 11,
sDisabled: false,
asd: null
};
},
methods: {
specialAttack() {
clearTimeout(this.asd); // Or as you suggest in comments you can disbale it here with replacing this: this.sDisabled = true
if (this.sTimer > 0) {
this.asd = setTimeout(() => {
this.sDisabled = true;
this.sTimer -= 1;
this.specialAttack();
}, 1000);
} else {
clearTimeout(this.asd);
this.sTimer = 11;
this.sDisabled = false;
}
}
},
created() {
this.specialAttack();
}
这是一个工作演示:
推荐阅读
- java - 子类“学生”和“讲师”的抽象方法
- asp.net - 使用 ckeditor 显示格式化文本的第一行
- r - 在 Ubuntu 16.04 上安装 R 3.5 时出现问题
- javascript - Node.js API 对不同 Recipient 的响应
- .htaccess - 如何允许来自 HTTP_REFERER 的引用并且不在 htaccess 中阻止 HTTP_USER_AGENT?
- python - 覆盖 Map 中使用的函数的默认参数
- r - ggplot2 两个填充两个不同的变量
- android-pdf-api - AndroidPdfViewer 在 KitKat 版本中不起作用
- matlab - 使用 textscan 将制表位读取为 4 个空格
- c# - 使用 Angular 6 将文件上传到 Web Api C#