Skip to content
Advertisement

Is there a way to exit an if statement from a setTimeout loop in JavaScript?

I am creating a percent clock that shows me how much percent I am through a certain time in the day. When I ran it, it had an output of above 100% when it was supposed to be 50% at the time. I realized the error was it wasn’t exiting the if statements, and I couldn’t figure out a way to do so. I can’t use while true statements because they don’t work with browsers, so if somebody could find a way to exit the if statement when the seconds variable gets above a certain amount I would be very grateful. Here is my code:

JavaScript
JavaScript
JavaScript

Advertisement

Answer

You need to clearInterval() every time you want to “exit” the loop. You also need to store the interval variable somewhere to be able to clear it:

See my // comments for the changes I made:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement