您好,登錄后才能下訂單哦!
小編給大家分享一下微信公眾號(hào)中如何實(shí)現(xiàn)倒計(jì)時(shí)的一個(gè)功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
代碼如下:
let interval = setInterval(() => { let {staticTime} = this.state; staticTime = staticTime - 1; if (staticTime <= 0) { clearInterval(interval); this.setState({ tip:'支付超時(shí)', staticTime:0 }); return; } let minutes = parseInt(staticTime/60); let Seconds = staticTime%60; let tip = '訂單已提交,請(qǐng)?jiān)?#39;+minutes+'分'+Seconds+'秒內(nèi)完成支付'; this.setState({ tip:tip, staticTime:staticTime }); }, 1000); 后來測試發(fā)現(xiàn)鎖屏或者把頁面留在后臺(tái),計(jì)算就不對(duì),于是把代碼進(jìn)行了如下改造。 let interval = setInterval(() => { let {backGroundTime, staticTime} = this.state; this.setState({ backGroundTime:0 }); staticTime = staticTime - backGroundTime - 1; if (staticTime <= 0) { clearInterval(interval); this.setState({ tip:'支付超時(shí)', staticTime:0, }); return; } let minutes = parseInt(staticTime/60); let Seconds = staticTime%60; let tip = '訂單已提交,請(qǐng)?jiān)?#39;+minutes+'分'+Seconds+'秒內(nèi)完成支付'; this.setState({ tip:tip, staticTime:staticTime, }); }, 1000); this.listenPageShowHideHandle(); //計(jì)算頁面在后臺(tái)的時(shí)間
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('時(shí)間差:', backGroundTime); } console.log( document.visibilityState ); });
}
改造之后發(fā)先問題依然存在。原因是: 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. **解決方案:** 訂單生成的時(shí)候我們記錄下這個(gè)時(shí)間為A, 時(shí)間間隔為B(3分鐘內(nèi)需要付款,B為3*60*1000),C為現(xiàn)在的時(shí)間。我們使用setInterval 每個(gè)1秒讀取一下時(shí)間。那么倒計(jì)時(shí)時(shí)間 == 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:'支付超時(shí)', isFalse:true }); return; } let minutes = parseInt(sub/60); let Seconds = sub%60; let tip = '訂單已提交,請(qǐng)?jiān)?#39;+minutes+'分'+Seconds+'秒內(nèi)完成支付'; console.log(tip); this.setState({ tip:tip, isFalse:false }); },1000);
以上是“微信公眾號(hào)中如何實(shí)現(xiàn)倒計(jì)時(shí)的一個(gè)功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。