Reputation: 287
How can I restart Interval after clearing it? I want a button to be clickable once every 11 seconds I made it disabled while timer is > 0 after it's equal to 0 button isn't disabled so it's clickable I wrote this code it seems to work but after multiple call of a setInterval()
function timer goes down too fast any soltuions>
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>
Upvotes: 0
Views: 55
Reputation: 10520
There are several mistakes you made here, so first of all to achieve such a thing you should use setTimeout
instead of setInterval
because interval generally will be repeated after a certain given time, so this may one of the possible reason for being called twice when you click your button as well. Then you need to create a generic function for this cause and then call it in document creation instead of creating two different intervals and calling them separately.
So with respecting these rules, your final code should be something like this:
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();
}
Here is a working demo:
Upvotes: 1