访客离开网站后继续倒数计时器

时间:2017-10-20 22:40:21

标签: javascript jquery timer

我的计时器在窗口加载时启动。访问者关闭我的网站页面后,计时器暂停。如果访问者在10小时后打开同一页面(带有计时器),则计时器将从之前暂停的同一时间开始。

即使访问者当前没有访问我的网站页面,我想创建一个3小时计时器在网站页面加载时启动并且在后台保持勾选

我希望将访问者重定向到另一个页面,然后说#34; amazon.com"在这3小时计时器到期后,如果他在3小时后访问该网站。



function countdown() {
  time = parseInt(localStorage.time);

  if(isNaN(time) || time > (38 * 60)) {
    //alert("An error occured: time left variable is corrupted, resetting timer");
    localStorage.time = 38 * 60;
    countdown();
    return null;
  }

  if(time <= 0) {
    alert("Your Timer Has Run Out! We Still Got 2 Discount Copies Left, Hurry Up!");
    return null;
  }

  var timers = document.getElementsByClassName('timeleft');

  Array.prototype.forEach.call(timers, function(timer) {
    timer.innerText = formatTime(time);
  })

  time--;
  localStorage.time = time;
  setTimeout('countdown()', 1000);
}

function formatTime(time) {
  minutes = Math.floor(time / 60);
  seconds = time - minutes * 60;

  if(String(seconds).length == 1) {
    return String(minutes) + ":0" + String(seconds);
  }

  return String(minutes) + ":" + String(seconds);
}

window.onload = function() {
  countdown();
}
&#13;
<font size="+34"><div class="timeleft"></div></font>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我认为您可以将开始时间存储在localStorage中,并将其与加载页面时的当前时间进行比较:

function startOrRedirect () {
  const startTime = localStorage.getItem('startTime')

  if (startTime) {
    const date1 = new Date(parseInt(startTime))
    const date2 = new Date()
    const hours = Math.abs(date1 - date2) / 36e5;

    if (hours >= 3) {
      redirect()
    }
  } else {
    localStorage.setItem('startTime', Date.now)
    setTimeout(redirect, 1000 * 60 * 60)
  }
}

function redirect () {
  window.location = 'https://amazon.com'
}

window.onload = startOrRedirect