Increase number with jquery and localstorage

1

I am using localstorage and getTime , to receive the time and save it in localstorage and then calculate if 1 minuto has passed and update localstorage and display a text in div . (I clarify that this is fake, hence the Math random and localstorage)

The problem I have is that when updating the page does not keep the text, I want to keep the text and that when the 60 seconds pass, it is simply updated (in this case when the person reloads the page) the changes.

function hasOneDayPassed(){
  var lastclear = localStorage.getItem('lastclear'),
      time_now  = (new Date()).getTime();
  // .getTime() returns milliseconds so 1000 * 60 = 60 sec
  if ((time_now - lastclear) > 1000 * 60) {
        localStorage.clear();
        localStorage.setItem('lastclear', time_now);
        $('#now-people').text( Math.floor(Math.random() * 20) + ' people are looking right now');   
  }
}

hasOneDayPassed(); // run the code
    
asked by Juan David 07.01.2018 в 15:01
source

2 answers

1

I have updated my code, so that I save the number of people and the time, when the time that has passed is evaluated, the items are assigned in localstorage and for people I use math random.

    function hasOneDayPassed() {
      var lastclear = localStorage.getItem('lastclear'),
        now_p = localStorage.getItem('now_p'),
        time_now = (new Date()).getTime();

      // .getTime() returns milliseconds so 1000 * 60 = 1 minute
      if ((time_now - lastclear) > 1000 * 60) {
        localStorage.clear();
        localStorage.setItem('lastclear', time_now);
        localStorage.setItem('now_p', Math.floor(Math.random() * 20));
      }
  $('#looking-now').html('<i class="fas fa-user"></i> ' + now_p + ' people are looking right now');
    }
    hasOneDayPassed(); // run the code
    
answered by 07.01.2018 в 19:05
0

To update the data every minute you can use the timeOut method.

setTimeout(function(){

 alert("Vamos a actualizar el dato"); 

}, 60000);
    
answered by 10.01.2018 в 15:58