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