萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 倒計時跳轉/重整頁面三種實作模式

模式一:倒計時自動重整頁面

<strong id="remainTime">10分00秒</strong>
<script>
var endTime = Date.now() + 10 * 60 * 1000; // 10 分鐘後
var blinkTitle = document.title;
var blink = 0;

function tick() {
  var left = endTime - Date.now();
  if (left <= 0) {
    document.getElementById("remainTime").textContent = "0分00秒";
    window.location.reload(); // 重整
    return;
  }
  var m = Math.floor(left / 60000);
  var s = Math.floor((left % 60000) / 1000);
  document.getElementById("remainTime").textContent = m + "分" + (s < 10 ? "0" : "") + s + "秒";
  setTimeout(tick, 1000);
}
tick();
</script>

模式二:倒計時跳轉指定網址

<span id="time" style="background:#00BFFF">3</span>秒後自動跳轉,
<a href="https://example.com">點此手動跳轉</a>
<script>
var sec = 3;
function countdown(url) {
  document.getElementById("time").textContent = sec;
  if (sec > 0) {
    sec--;
    setTimeout(function() { countdown(url); }, 1000);
  } else {
    window.top.location.href = url;
  }
}
countdown("https://example.com");
</script>

模式三:防重整倒計時(利用 window.name 跨頁保持狀態)

<div id="timer" style="color:red"></div>
<script>
var maxTime = window.name === "" ? 60 : parseInt(window.name, 10); // 秒

function countDown() {
  if (maxTime >= 0) {
    var m = Math.floor(maxTime / 60);
    var s = maxTime % 60;
    document.getElementById("timer").textContent = "距離結束還有 " + m + "分" + s + "秒";
    if (maxTime === 300) alert("注意,還有 5 分鐘!");
    maxTime--;
    window.name = maxTime; // 存入 window.name 保持跨刷新
  } else {
    clearInterval(timer);
    alert("時間到!");
  }
}
var timer = setInterval(countDown, 1000);
</script>

原理:window.name 在同一分頁/視窗內跨頁面導航仍保持數值,可用於簡易狀態保存(但不建議存放敏感資料)。

比較表

模式適用場景關鍵 API
重整定期輪詢、儀表板自動更新location.reload()
跳轉倒計時進入正式頁、廣告頁location.href / top.location.href
防重整線上考試、限時活動window.name + setInterval
copyright © 萬盛學電腦網 all rights reserved