您好,登錄后才能下訂單哦!
小編給大家分享一下微信公眾號中如何實現倒計時的一個功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
代碼如下:
let interval = setInterval(() => { let {staticTime} = this.state; staticTime = staticTime - 1; if (staticTime <= 0) { clearInterval(interval); this.setState({ tip:'支付超時', staticTime:0 }); return; } let minutes = parseInt(staticTime/60); let Seconds = staticTime%60; let tip = '訂單已提交,請在'+minutes+'分'+Seconds+'秒內完成支付'; this.setState({ tip:tip, staticTime:staticTime }); }, 1000); 后來測試發現鎖屏或者把頁面留在后臺,計算就不對,于是把代碼進行了如下改造。 let interval = setInterval(() => { let {backGroundTime, staticTime} = this.state; this.setState({ backGroundTime:0 }); staticTime = staticTime - backGroundTime - 1; if (staticTime <= 0) { clearInterval(interval); this.setState({ tip:'支付超時', staticTime:0, }); return; } let minutes = parseInt(staticTime/60); let Seconds = staticTime%60; let tip = '訂單已提交,請在'+minutes+'分'+Seconds+'秒內完成支付'; this.setState({ tip:tip, staticTime:staticTime, }); }, 1000); this.listenPageShowHideHandle(); //計算頁面在后臺的時間
listenPageShowHideHandle = () =>{
let {backGroundTime} = this.state; let start, end; let self = this; document.addEventListener("visibilitychange", function() { if(document.visibilityState == 'hidden'){ start = new Date().getTime(); }else if(document.visibilityState == 'visible'){ end = new Date().getTime(); backGroundTime = Math.floor((end - start)/1000); self.setState({backGroundTime}); console.log('時間差:', backGroundTime); } console.log( document.visibilityState ); });
}
改造之后發先問題依然存在。原因是: You cannot continue to run javascript while the iPhone is sleeping using setTimeout(), however.When the phone is put to sleep, Safari will kill any running javascript processes using setTimeout(). Check out this answer here for some reasons why this is done. **解決方案:** 訂單生成的時候我們記錄下這個時間為A, 時間間隔為B(3分鐘內需要付款,B為3*60*1000),C為現在的時間。我們使用setInterval 每個1秒讀取一下時間。那么倒計時時間 == A+B-C,代碼如下 let interval = setInterval(()=>{ let {orderTime, staticTime} = this.state; let nowTime = Date.now(); let sub = Math.floor((orderTime + staticTime - nowTime)/1000); console.log('sub',sub); if(sub<=0){ clearInterval(interval); this.setState({ tip:'支付超時', isFalse:true }); return; } let minutes = parseInt(sub/60); let Seconds = sub%60; let tip = '訂單已提交,請在'+minutes+'分'+Seconds+'秒內完成支付'; console.log(tip); this.setState({ tip:tip, isFalse:false }); },1000);
以上是“微信公眾號中如何實現倒計時的一個功能”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。