首页 > 解决方案 > 清除后重新开始间隔

问题描述

清除后如何重新启动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>

标签: javascriptvue.jsvuejs2

解决方案


你在这里犯了几个错误,所以首先要实现这样的事情你应该使用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();
}

这是一个工作演示:

代码沙盒


推荐阅读