【问题标题】:Countdown 1 hour using localstorage JavaScript not working as intended使用 localstorage JavaScript 倒计时 1 小时未按预期工作
【发布时间】:2022-11-25 04:33:28
【问题描述】:

我正在尝试将倒数计时器设置为 1 小时,当该小时结束时,计时器应将人们重定向到特定页面。

我当前的代码没有按预期工作,因为它没有在刷新页面后将倒计时存储在 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 );

【问题讨论】:

  • 有没有其他方法可以做上面提到的同样的事情?

标签: javascript


【解决方案1】:
// 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

【讨论】:

  • 另外,我建议使用 session storage 来确保一定程度的数据安全,除非并且直到您允许您的应用程序具有多选项卡功能
【解决方案2】:

我做了一些改变,但它是相似的,希望它对你有用。

<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>

【讨论】:

    【解决方案3】:
    // 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2021-10-30
      • 2017-04-23
      • 1970-01-01
      • 2016-11-25
      • 2020-04-10
      相关资源
      最近更新 更多