LlamaButt
LlamaButt

Reputation: 471

Save time left on setInterval() after reloading page?

I am making a webpage that is supposed to serve as a place to take a break, and all html elements will hide after 5 minutes and show again after 30, but currently this cooldown can be bypassed by simply reloading the page. I was going to try using localStorage.setItem(), but I'm not sure how I would get the time left on the interval to save or update it. my code is here.

<script>

var body = document.querySelector('body')
    
    setInterval(()=>{
        body.style.display = 'initial' ;
        setTimeout(()=>{
              body.style.display = 'none'
        }, 300000)
     }, 180000)


</script> 
<body>
<h1>example html</h1>

</body

Upvotes: 1

Views: 414

Answers (1)

mplungjan
mplungjan

Reputation: 178285

Perhaps something like this

const body = document.querySelector('body');
const aMinute = 60000;
let d = localStorage.getItem("d"); 
let now = new Date().getTime;
let end = d ? new Date(d) : new Date().getTime();
let tId = setInterval(()=>{
  now = new Date().getTime;
  body.classList.toggle("initial",now-end > 0);
}, 180000)
// some event to set
localStorage.setItem("d",(new Date().getTime()+5*aMinute));
<h1>example html</h1>

Upvotes: 1

Related Questions