这个倒计时按钮,若是页面在移动端切到后台和切回来,倒计时中止运行。
可是在pc端没有这个问题。
倒计时代码以下javascript
let downCount = () => { if (this.count >= 1) { this.count--; } else { clearInterval(timer); } }; timer = setInterval(downCount , 1000);
页面切到后台会触发 visibilitychange 事件,经过document监听器能够捕获这个事件
Document.visibilityState 能够得到当前状态java
https://developer.mozilla.org...浏览器
let downCount = () => { if (this.count >= 1) { this.count--; } else { clearInterval(timer); } }; document.addEventListener('visibilitychange',() => { if(document.visibilityState == 'hidden'){ clearInterval(timer);//为了兼容pc,pc切换到后台继续运行 start= new Date().getTime(); } else if( document.visibilityState == 'visible'){ end = new Date().getTime(); s2 =Math.floor( (end - start)/1000); this.count = this.count - s2; timer = setInterval(downCount , 1000); document.removeEventListener('visibilitychange'); } }) timer = setInterval(downCount , 1000);