简体   繁体   English

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

[英]Continue Countdown Timer after visitor leaves website

My timer starts on window load. 我的计时器从窗口加载开始。 After a visitor closes my website page the timer pauses. 访问者关闭我的网站页面后,计时器暂停。 If the visitor opens the same page (with timer) after 10 hours, the timer starts from the same time where it had paused earlier. 如果访客在10小时后打开同一页面(带有计时器),则计时器将从先前暂停的同一时间开始。

I want to create a 3 hour timer that starts when website page is loaded and that keeps ticking in the background even if the visitor is not currently visiting my website page. 我想创建一个3小时的计时器,该计时器从加载网站页面时开始,即使访问者当前未访问我的网站页面,它也始终在后台计时

I wish to redirect the visitor to another page say "amazon.com" after this 3 hour timer has expired, if he visits the website AFTER 3 hours. 如果3小时后访问者访问网站,我希望在3小时定时器到期后将访问者重定向到另一个页面,例如“ amazon.com”。

 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(); } 
 <font size="+34"><div class="timeleft"></div></font> 

I think you can just store the start time in localStorage , and compare it to the current time whenever the page is loaded: 我认为您可以将开始时间存储在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM