setInterval Restart when page is Refreshed

痴心易碎 提交于 2020-01-25 07:57:07

问题


I have the following code to set a counter of tickets sold by increasing the number with a random amount:

let tickets = 35000;
const contador = document.querySelector('.contador');

let interval = setInterval(function(){
  console.log(tickets);

  if (tickets >= 60000) {

    var textoTodoVendido = `<p>¡Todo vendido!</p>`;
    contador.innerHTML = textoTodoVendido;
    console.log("Sold out");
    clearInterval(interval);

  }else{
    var texto = `¡${tickets} entradas vendidas!`;
    contador.innerHTML = texto;
    console.log(texto)
  }

  const random = Math.floor(Math.random()*(200-100+1)+100);
  tickets += random;


}, 10000);

The thing is that everytime a user enter in the site, it's showed 35000, and I want to show the amount increased since I set the setInterval at the first time: i.e: I set the interval and the amount reach 35987, so I want the user to see this amount, not every user start within 35000. And whenever they refresh, the amount continue increasing from the amount displayed before the page refresh.

So, can someone help me out to solve this? Really appreciate.

I found the following code by setting local storage, but it doesn't work to me:

  var key = '_timeInMs_' + (name || '');
  var now = Date.now();
  var timeInMs = localStorage.getItem(key);
  var executeCallback = function () {
    localStorage.setItem(key, Date.now());
    callback();
  }
  if (timeInMs) { // User has visited
    var time = parseInt(timeInMs);
    var delta = now - time;
    if (delta > interval) { // User has been away longer than interval
      setInterval(executeCallback, interval);
    } else { // Execute callback when we reach the next interval
      setTimeout(function () {
        setInterval(executeCallback, interval);
        executeCallback();
      }, interval - delta);
    }
  } else {
    setInterval(executeCallback, interval);
  }
  localStorage.setItem(key, now);
} 




来源:https://stackoverflow.com/questions/59881219/setinterval-restart-when-page-is-refreshed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!