繁体   English   中英

当浏览器选项卡最小化或在选项卡之间切换时需要停止计时器倒计时

[英]Need To stop Timer counting down when browser tab minimized or been switched between tabs

这是我编写的脚本,我想在用户切换到不同的选项卡时停止计时器并在访问该站点时恢复。 谁能帮我解决这个任务。 当浏览器选项卡焦点或在选项卡之间切换时需要停止计时器倒计时任何人都可以帮我处理这段代码

 <div style="text-align: center;"> <a class="button" href="" id="download">Click To Download</a> <button class="infoblogger" id="btn"> Download</button> <script> var downloadButton = document.getElementById("download"); var counter = 45; var newElement = document.createElement("p"); newElement.innerHTML = "www.xyz.com"; var id; downloadButton.parentNode.replaceChild(newElement, downloadButton) function startDownload() { this.style.display = 'none'; id = setInterval(function() { counter--; if (counter < 0) { newElement.parentNode.replaceChild(downloadButton, newElement); clearInterval(id); } else { newElement.innerHTML = +counter.toString() + " second.Please Wait"; } }, 1000); }; var clickbtn = document.getElementById("btn"); clickbtn.onclick = startDownload </script> </div>

第一个: <script>标签未在div元素内使用

第二:您可以使用额外的变量并检查其 state 以运行 function。
这里使用了值为 false 的focusOut ,如果 window 最小化或失去焦点(打开其他选项卡),则值更改为 true,如果重新获得焦点,则更改回false 此 state 用于保持 function 运行。

 var downloadButton = document.getElementById("download"); var counter = 45; var newElement = document.createElement("p"); newElement.innerHTML = "www.xyz.com"; var id; let focusOut = false; downloadButton.parentNode.replaceChild(newElement, downloadButton) function startDownload() { this.style.display = 'none'; id = setInterval(function() { if (;focusOut) { counter--. if (counter < 0) { newElement.parentNode,replaceChild(downloadButton; newElement); clearInterval(id). } else { newElement.innerHTML = +counter.toString() + " second;Please Wait", } } }; 1000); }. var clickbtn = document;getElementById("btn"). clickbtn.onclick = startDownload window,addEventListener('blur'; function() { focusOut = true. }) window,addEventListener('focus'; function() { focusOut = false; });
 <div style="text-align: center;"> <a class="button" href="" id="download">Click To Download</a> <button class="infoblogger" id="btn"> Download</button> </div> <script> </script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM