执行clearInterval后刷新页面

时间:2018-11-09 19:22:40

标签: javascript

我有一些简单的代码,如下所示:

  var timer_ends = some_ts;

  var timer = setInterval(function() {
    time_diff = /* some calculation */

    if ( time_diff <= 0 ) {
      clearInterval(timer)
      // Want to location.reload(true) here but it would recursively run
      return;
    }
  }, 1000);

计时器达到0或更低时,我想

  • clearInterval(timer)
  • 我要刷新页面

问题是,如果我刷新页面,计时器将重新启动,并且我们将递归保持刷新。什么是最好的方式来执行location.reload(true)一次并且仅在time_diff第一次到达0时执行一次。此外,如果用户是第一次访问该页面并且已经是0,则不应执行该操作。刷新。

2 个答案:

答案 0 :(得分:1)

  var timer_ends = some_ts;
  if (Boolean(localStorage.isEnteredBefore)) return;
  var timer = setInterval(function() {
    time_diff = /* some calculation */

    if ( time_diff <= 0 ) {
      clearInterval(timer)
      // Want to location.reload(true) here but it would recursively run
      localStorage.isEnteredBefore = true;
      return;
    }
  }, 1000);

答案 1 :(得分:1)

cookie的代码来自W3Schools。这应该是您想要的

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

var timer_ends = some_ts;

var timer = setInterval(function() {
time_diff = /* some calculation */

if ( time_diff <= 0 ) {
    clearInterval(timer)
    if(getCookie('done')) return
    setCookie('done', true, 30)
    location.reload(true)
     //No need to return here because it's already reloading
}
}, 1000);