简体   繁体   English

使用 localstorage JavaScript 倒计时 1 小时未按预期工作

[英]Countdown 1 hour using localstorage JavaScript not working as intended

I'm trying to make an countdown timer set to 1 hour, when the hour is done, the timer should redirect people to a specific page.我正在尝试将倒数计时器设置为 1 小时,当该小时结束时,计时器应将人们重定向到特定页面。

My current code is not working as intended since its not storing in localstorage the countdown after a refresh of the page.我当前的代码没有按预期工作,因为它没有在刷新页面后将倒计时存储在 localstorage 中。

<div id='stored'></div>

<script>


function countdown(minutes, seconds )
{
    var endTime, hours, mins, msLeft, time;

    function twoDigits( n )
    {
        return (n <= 9 ? '0' + n : n);
    }

    function updateTimer()
    {
        msLeft = endTime - (+new Date);
        if ( msLeft < 1000 ) {
          window.location.replace('done');
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            localStorage.setItem('timelol', (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() ));
            document.getElementById('stored').innerHTML = localStorage.getItem('timelol');
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }


    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}
countdown( 60,0 );
// checks if expirationTime is present on initial and subsequent page loads

if (!localStorage.getItem("exp")) {
  const expirationTimeInHours = 1;

  const expirationTime = Date.now() + expirationTimeInHours * 60 * 60 * 1000; 
  // expirationTime = current time in millsec + 1hr in millsec
  console.log("expirationTime", expirationTime);

  localStorage.setItem("exp", expirationTime);
}

// Execute checkExpiration() function on page Load
const checkExpiration = setInterval(() => {
  const currentTime = Date.now();
  const expireAt = localStorage.getItem('exp');
  console.log('current', currentTime);
  if (currentTime >= expireAt) {
    //do some action
    console.log("expired");
    clearInterval(checkExpiration);
  }
}, 5000); // every 5sec - change as per your need

I made a few changes, but it's similar, hope it works for you.我做了一些改变,但它是相似的,希望它对你有用。

<div id='stored'></div>
<div id='started'></div>


<script>

let startTime = sessionStorage.getItem("LastTime"); // timelol
if (startTime == null){
    startTime = +new Date;
    sessionStorage.setItem("LastTime", startTime);
}


document.getElementById("started").innerHTML = startTime;


function countdown(minutes, seconds )
{
    var hours, mins, msLeft, time;
    var tot_sec = minutes * 60 + seconds;

    function twoDigits( n )
    {
        return (n <= 9 ? '0' + n : n);
    }

    function updateTimer()
    {
        //console.log("Start Time = " + startTime);

        var rightNow = +new Date;
        //console.log("Now        = " + rightNow);

        var dif_Date = rightNow - startTime;
        //console.log("Difft Time = " + dif_Date);

        var rest_seconds = tot_sec - Math.round((rightNow - startTime)/1000);
        console.log("Left Sec   = " + rest_seconds);

        if (rest_seconds < 1){
            window.location.replace('done');
        }else{
            time = new Date(tot_sec*1000 - dif_Date );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            var result_time = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
            document.getElementById('stored').innerHTML = result_time;

            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    updateTimer();
}

countdown( 60, 0 );

</script>
// Try this code! It's working fine!

const divTimer = document.getElementById("stored");
const time = "01:00:00";

if (!localStorage.getItem("@App:currentStamp")) {
  localStorage.setItem("@App:currentStamp", `${time}`);
}

const start = setInterval(countdown, 1000);

function countdown() {
  currentStamp = localStorage.getItem("@App:currentStamp");
  if (currentStamp === "00:00:00") {
    localStorage.removeItem("@App:currentStamp");
    divTimer.innerHTML = "Redirecting...";
    stop();
    location.href = "http://www.google.com/"
    return
  }

  let hours = currentStamp.split(":")[0];
  let minutes = currentStamp.split(":")[1];
  let seconds = currentStamp.split(":")[2];

  const now = new Date();
  let currentTime = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDay(),
    hours,
    minutes,
    seconds,
    0
  );

  currentTime.setSeconds(currentTime.getSeconds() - 1);
  localStorage.setItem(
    "@App:currentStamp",
    `${new String(currentTime.getHours()).padStart(2, "0")}:${new String(
      currentTime.getMinutes()
    ).padStart(2, "0")}:${new String(currentTime.getSeconds()).padStart(
      2,
      "0"
    )}`
  );
  divTimer.innerHTML = localStorage.getItem("@App:currentStamp");
}

function stop() {
  clearInterval(start);
}

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

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