簡體   English   中英

純 JavaScript:如果瀏覽器選項卡處於活動狀態,如何在倒計時后刷新頁面

[英]Pure JavaScript: How to refresh page after countdown if the browser tab is active

我想實現以下場景:

設置 60 秒的計時器並開始顯示計時器的倒計時。 倒計時結束后,刷新(不是重新加載)頁面並重新啟動倒計時計時器並繼續該過程。

If the browser's tab is changed, after finishing the timer, refresh the page and pause the timer, and only when the tab is active again refresh the page and start the countdown timer again.

我已經設法實現了第一個要求,例如:

Result will Refresh in <span id="countdown"></span>
<script>
  if (!document.hidden) {
    function timedRefresh(e) {
      var n = setInterval((function () {
        e > 0 ? (e -= 1, document.getElementById("countdown").innerHTML = e) : (clearInterval(n), window.location.reload())
      }), 1e3)
    }
    timedRefresh(59)
  }
</script>

而無法達到第二個要求。 我已嘗試實施此處提到的解決方案: Is there a way to detect if a browser window is not currently active? 但它沒有用。

如何在純 JavaScript 代碼中實現要求?

下面的代碼解決了這個場景。 有點亂,但我覺得可以理解。 我們同時使用window.document.hasFocus()和焦點事件來創建此解決方案。 我已將window.location.reload()方法更改為僅控制台模擬 function 刷新應用程序內的數據,因為要求我們刷新(而不是重新加載)

    function timedRefresh(intervalTime) {
        let interval = null;
        let currentTime = intervalTime;

        const updateTimer = () => {
            const countdownSpan = document.getElementById("countdown");

            if (currentTime <= 0) {
                console.log(`print refresh at ${new Date()}`); // refresh page
                if (window.document.hasFocus()) {
                    currentTime = intervalTime;
                } else {
                    clearInterval(interval);
                    interval = null;
                    currentTime = intervalTime;
                }
            }

            if (!interval) {
                countdownSpan.innerHTML = "#";
            } else {
                countdownSpan.innerHTML = currentTime;
                currentTime -= 1;
            }
        };

        interval = setInterval(updateTimer, 1000);
        window.addEventListener("focus", () => {
            if (!interval) {
                interval = setInterval(updateTimer, 1000);
            }
        });
    }

    const TIMER_SECONDS = 5;
    timedRefresh(TIMER_SECONDS);

編輯:

上面的答案不適用於使用window.location.realod()重新加載。 解決問題的代碼可能如下所示:

  const TIMER_SECONDS = 60;

/* 
 * Update span with current time
 *  `currentTime` is an integer bigger than zero or a string '#' meaning 'timer stopped'
 */
function updateDisplayTimer(currentTime){
  const countdownSpan = document.getElementById("countdown");
  countdownSpan.innerHTML = currentTime;
}

/*
 * A timer with `loopDuration` seconds. After finished, the timer is cleared.
 *  `loopDuration` is an integer bigger than zero, representing the time duration in seconds.
 */
function timedRefresh(loopDuration) {

  let currentTime = loopDuration;
  let interval = setInterval(() => {
    if (currentTime > 0) {
      updateDisplayTimer(currentTime);
      currentTime -= 1;
    } else {
      window.location.reload(); // refresh page
    }
  }, 1000);

  window.addEventListener('load', () => {
    if(window.document.hasFocus()){
      timedRefresh(TIMER_SECONDS);
    } else {
      updateDisplayTimer("#");
      clearInterval(interval);
      interval = null;
    }
  });

  window.addEventListener('focus', () => {
    if(interval == null){
      window.location.reload(); // refresh page
    }
  });
}

// exeute main fucntion 
timedRefresh(TIMER_SECONDS);

使用window.document.hasFocus()來確定用戶是否專注於您的網頁。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM