This question already has answers here:
Is there a way to detect if a browser window is not currently active?
                                
                                    (18个答案)
                                
                        
                                在11个月前关闭。
            
                    
大家好,我是JavaScript的新手,我想拥有一个倒计时,该倒计时在页面加载时自动开始,并且仅在页面聚焦时才能恢复。这是一个示例http://hp30405.pythonanywhere.com/mz7z5/

如何在setTimeout(function() {});中使用相同的逻辑?

这是我的脚本:

$(window).load(function() {
    var timeleft = 20;
    var downloadTimer = setInterval(function(){
    document.getElementById("timer").innerHTML = timeleft ;
    timeleft -= 1;
    if(timeleft < 0){
        clearInterval(downloadTimer);
        document.getElementById("timer").innerHTML = "20 sec done"
    }
    }, 1000);

      setTimeout(function() {
        $("#submit").removeAttr("disabled");
        }, 22000);
});

最佳答案

您将$(window).blur()$(window).focus()用于clearIntervalsetInterval
不幸的是,它在代码段中不起作用,但在代码段外正常工作



let downloadTimer;
var timeleft = 20;
downloadTimer = setInterval(countDown,1000)
function countDown(){
  document.getElementById("timer").innerHTML = timeleft ;
  timeleft -= 1;
  if(timeleft < 0){
	clearInterval(downloadTimer);
	document.getElementById("timer").innerHTML = "20 sec done"
  }
}

$(window).blur(function(){
  console.log("blurred")
  clearInterval(downloadTimer);
})
$(window).focus(function(){
	console.log("focuesed")
	downloadTimer = setInterval(countDown,1000);
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer"></div>

关于javascript - 页面未聚焦时停止倒计时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54616014/

10-10 22:35