這個倒計時按鈕,若是頁面在移動端切到後臺和切回來,倒計時中止運行。
可是在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);