Reputation: 33
I am unable to reset the setInterval function in ts. I have tried clearInterval but that just stops the interval. I have also tried setting it to undefined but has not helped.The usecase is basically to find timeinterval between two websocket inputs and check if it is less than two minutes. But what ends up happening is the timer keeps going faster.
function {
this.timeLeftForPlantThree = 120;
const a = 1000;
let interval3;
clearInterval(interval3);
interval3 = undefined;
if (typeof(interval3) === 'undefined') {
interval3 = setInterval(() => {
if (this.timeLeftForPlantThree > 0) {
this.timeLeftForPlantThree--;
this.plantThreeRed = false;
console.log(this.timeLeftForPlantThree);
} else {
console.log('***' + this.timeLeftForPlantThree);
this.plantThreeRed = true;
}
}, a);
}
}
Upvotes: 1
Views: 71
Reputation: 9355
Assign your interval to a variable and reset it then:
this.interval = setInterval(() => {
// do something here
}, 1000);
And reset:
if (this.interval) clearInterval(this.interval);
this.interval = null;
Regarding your code, you are creating empty variable/ interval and then clearing it which throws error.
And declare variable for the interval globally.
let interval3;
And run it inside function:
function runInterval() {
this.timeLeftForPlantThree = 120;
const a = 1000;
if (!this.interval3) {
this.interval3 = setInterval(() => {
if (this.timeLeftForPlantThree > 0) {
this.timeLeftForPlantThree--;
this.plantThreeRed = false;
console.log(this.timeLeftForPlantThree);
} else {
console.log('***' + this.timeLeftForPlantThree);
this.plantThreeRed = true;
}
}, a);
}
}
And the reset it:
function resetInterval() {
if (this.interval) clearInterval(this.interval);
this.interval = null;
}
Upvotes: 0
Reputation: 2623
You are making something strange with that interval!
var interval3 = setInterval(() => {});
function {
this.timeLeftForPlantThree = 120;
const a = 1000;
interval3 = setInterval(() => {
// call clear interval here when some condition is satisfied
if (this.timeLeftForPlantThree > 0) {
this.timeLeftForPlantThree--;
this.plantThreeRed = false;
console.log(this.timeLeftForPlantThree);
} else {
console.log('***' + this.timeLeftForPlantThree);
this.plantThreeRed = true;
}
}, a);
}
Upvotes: 0