-3

i'm just starting out with javascript and I'm trying to make some sort of dashboard. I would like the fuel status to go down by 1 every few seconds but i want it to stop at zero. Also, i was trying to set an alert when the fuel status reaches 20%, but obviously it doesnt work.

I have a few questions: How can i "stop" the setInterval function when fuelStatus reaches 0? I dont think i fully understand the topic with the functions so i believe my approach may not be correct. Do i need to write functions for every task that i want to do like checking the fuel? Should i have put testFuel in the fuelStatus function?

Thanks guys!

var fuelStatus = 100;
function Fuel() {

    fuelStatus--; //number = -1;
    console.log(fuelStatus);
    document.getElementById("fuelStatus").innerHTML = fuelStatus + '%';

}

setInterval(function() {
    Fuel()
}, 5000)



function testFuel() {
    if (fuelStatus == 20) {
        alert("critical fuel status")
    }

}
  • You can use [`clearInterval(intervalID)`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval). You can assign your interval to a variable and that will become your interval ID (`const foo = setInterval(...)`) – secan Jun 10 '21 at 12:57
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – rook218 Jun 10 '21 at 12:58

1 Answers1

1

Capture the ID returned by setInterval() and then use the clearInterval function, passing it the captured interval ID, to clear it.

var fuelStatus = 100;
function Fuel() {

    fuelStatus--; //number = -1;
    console.log(fuelStatus);
    document.getElementById("fuelStatus").innerHTML = fuelStatus + '%';

}

const runFuelInterval = setInterval(function() {
    Fuel()
}, 5000)



function testFuel() {
    if (fuelStatus == 20) {
        alert("critical fuel status")
        clearInterval(runFuelInterval);
    }

}
cmcculloh
  • 47,596
  • 40
  • 105
  • 130