如何实现浏览器标签页切换/最小化时暂停倒计时、返回页面后自动恢复
解决方案
实现逻辑
- 采用浏览器内置的
Page Visibility API监听标签页的可见状态变动,兼容性覆盖所有现代浏览器 - 新增状态标记变量区分倒计时是否处于运行中,避免未触发倒计时时出现异常操作
- 标签页失焦/最小化时清空定时器暂停计数,用户重新切回当前标签页时若倒计时未结束则自动重启定时器继续计数
完整修改代码
<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; var isCounting = false; // 新增:标记倒计时是否正在运行 downloadButton.parentNode.replaceChild(newElement, downloadButton) function startDownload() { this.style.display = 'none'; isCounting = true; runCountdown(); // 封装倒计时逻辑复用 }; // 封装倒计时执行逻辑,方便暂停后重新调用 function runCountdown() { id = setInterval(function() { counter--; if (counter < 0) { newElement.parentNode.replaceChild(downloadButton, newElement); clearInterval(id); isCounting = false; } else { newElement.innerHTML = counter.toString() + " second.Please Wait"; } }, 1000); } // 监听标签页可见状态变化 document.addEventListener('visibilitychange', function() { // 倒计时未启动或者已经结束的情况下直接跳过 if (!isCounting || counter < 0) return; if (document.hidden) { // 标签页不可见,清空定时器暂停计时 clearInterval(id); } else { // 标签页重新可见,恢复倒计时 runCountdown(); } }) var clickbtn = document.getElementById("btn"); clickbtn.onclick = startDownload </script> </div>
内容的提问来源于stack exchange,提问作者Thiz is Sam
相关产品推荐
相关产品推荐

