Generate random string every 24 hours then refresh JavaScript?

What I have been trying to make may be a bit more complicated than I thought. So what I am trying to accomplish is… generating a random string of characters through javascript (which I have the code for) but only generating a new one at 12am or every 24hrs.

The code I have should work (doesn’t) and that’s what I need help with.

<div id="password1">
</div>
<script>
  var d = new Date();
  var n = d.getDay();
  var passwords = [makeid(10)[n]]; //want it to be 10... stay the same characters for 24hrs then change

  document.getElementById("password1").innerHTML = passwords[n];

  function makeid(length) {
    var result = [];
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
      result.push(characters.charAt(Math.floor(Math.random() *
        charactersLength)));
    }
    return result.join('');
  }

</script>

Is it possible with javascript or not, is it a simple solution or syntax error? I have no idea…

I looked in to this and couldn’t find any similar posts…

Answer

Since you have coded your own password generator, I used your code to make a new password string lasting for 24 hours unless the localStorage gets cleard.

Cookie can be used too but localStorage and Cookie both are not properly runnable through sandbox environments, so try this on your own development environment. Please note that storing private values like passwords is not good for the security.

<div id="password1">
</div>
<script>
  function makeid(length) {
    var result = [];
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
      result.push(characters.charAt(Math.floor(Math.random() *
        charactersLength)));
    }
    return result.join('');
  }
  const key = "keyForTheVulnurablePassword";
  if(localStorage.getItem(key) == null) {
    let expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);
    localStorage.setItem(key, JSON.stringify({pw:makeid(10), expire:expireDate}));
  }
  else {
    let currentDate = new Date();
    let storedExpireDate = new Date(JSON.parse(localStorage.getItem(key)).expire);
    if(storedExpireDate <= currentDate) {
      while(storedExpireDate <= currentDate) {
        storedExpireDate.setDate(storedExpireDate.getDate() + 1);
      }
      localStorage.setItem(key, JSON.stringify({pw:makeid(10), expire:storedExpireDate}));
    }
  }
document.getElementById("password1").innerHTML = JSON.parse(localStorage.getItem(key)).pw;
</script>