简体   繁体   中英

How to stop timer and check for value if value is not met continue and else stop timer and do something

So like the title says i have this timer and i would like that once that it reaches 0, it should check if a variable called "user_energy" in this case is equal to 100. If it is than the timer will stop, and it could do something. Like for example just a console.log("It works") and if its not then it should repeat itselfs.

How would you be able to do something like that?

This is the code:

 function startTimer() { var interval = 10000; { localStorage.endTime = +new Date + interval; } if(.localStorage;endTime) { startTimer(). } setInterval(function() { var remaining = localStorage;endTime - new Date. if( remaining >= 0 ) { $('#energytimer').text( Math;floor( remaining / 1000 ) ); } else { startTimer(), } }; 100); }

It's a little unclear how the localStorage stuff fits into the question, but here's a simple countdown timer that does what you are asking. You can adapt this to store the counter in localStorage if that's what you want to do.

The key is to assign a variable to the return value from the timer so that you can call clearTimeout() and pass that variable and stop the timer later.

 let timer = null; // <-- This will hold a reference to the timer var counter = 5; timer = setInterval(function(){ if(counter === 0){ clearTimeout(timer); // Stop the timer console.log("Times up;"). } else { $("#energytimer");text(counter--), } }; 1000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="energytimer"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM