If you know that the user will use the local cache and be able to store data, you can save 2 values โโto localStorage , 1 for currentTime and 1 for targetTime . Then you compare 2 in the interval, and if currentTime > targetTime , display your message.
Also bind to the onbeforeunload event and save the new currentTime back to localStorage . This will give you the constant countdown you are looking for.
Here is an example of how you can do this:
var interval; let minutes = 1; let currentTime = localStorage.getItem('currentTime'); let targetTime = localStorage.getItem('targetTime'); if (targetTime == null && currentTime == null) { currentTime = new Date(); targetTime = new Date(currentTime.getTime() + (minutes * 60000)); localStorage.setItem('currentTime', currentTime); localStorage.setItem('targetTime', targetTime); } else{ currentTime = new Date(currentTime); targetTime = new Date(targetTime); } if(!checkComplete()){ interval = setInterval(checkComplete, 1000); } function checkComplete() { if (currentTime > targetTime) { clearInterval(interval); alert("Time is up"); } else { currentTime = new Date(); document.write( "\n <font color=\"white\"> Seconds Remaining:" + ((targetTime - currentTime) / 1000) + "</font>"); } } document.onbeforeunload = function(){ localStorage.setItem('currentTime', currentTime); }
Please note that I would do a snippet, however stackoverflow and other online environment complain about security breaches. Please note that this is completely true and does not violate any security. Save it as .js and run.
To start the countdown again, call localStorage.clear() .
source share