0

I'm making a function to clear my local storage every month and set a 25 hour cooldown timeout so it wont activated again after executed but always got reset and keep executed everytime. Please help to fix this. Thanks

let cooldown = false;
const RECHARGE_TIME = 90000000; //25 hour cooldown
let today = new Date()
document.getElementById("todayDate").innerHTML = today.getDate();

if(today.getDate() === 1 && !cooldown){  
    clearHighScore();
    startCooldown();
}

console.log(cooldown) //just to check the cooldown state

function clearHighScore() {
    localStorage.clear();
}

function startCooldown() {
    cooldown = true;
    setTimeout (function(clearHighScore){ cooldown = false}, RECHARGE_TIME);
}
  • You would have to keep the browser tab open for 25 hours for that setTimeout to work. –  Mar 29 '21 at 08:42
  • @ChrisG know other way to make the timeout to work without closing or refreshing the tab? thanks – Novan Noviandri Sumarna Mar 29 '21 at 08:43
  • what do you mean everytime? if you refresh your page, the js is reloaded, and cooldown will be false again, so the if block will be executed again – lam Mar 29 '21 at 08:46
  • You could use something like `localStorage.setItem('cleared', 'yes')`, and if the page is visited on the first of a month, just check for that. –  Mar 29 '21 at 08:46
  • @lam yes that. Looking for a way to keep the cooldown going when the page is refreshed. – Novan Noviandri Sumarna Mar 29 '21 at 08:48
  • What is the purpose of the cooldown? If it is invalidated every month, why do those 24 hours matter? Also your script wont clear anything if the page isn't opened on the first day of the month. (Say when it is a weekend day.) – Ivar Mar 29 '21 at 08:51
  • @Ivar I'm trying to keep the localStorage.clear function to be executed only once so setting the 24 hour timeout cooldown so it wont executed when the page visited again in the same day after executing. The point is I want to automaticly clear the local storage once a month – Novan Noviandri Sumarna Mar 29 '21 at 08:55
  • Try [this answer](https://stackoverflow.com/a/4275854). Based on the stored date and the current date, you can calculate how much time has past and whether that exceeds a month. If this is the case you can either remove it, or overwrite the value, or simply ignore it. – Ivar Mar 29 '21 at 09:08

0 Answers0