小编给大家分享一下微信公众号中如何实现倒计时的一个功能,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
创新互联自成立以来,一直致力于为企业提供从网站策划、网站设计、网站建设、网站设计、电子商务、网站推广、网站优化到为企业提供个性化软件开发等基于互联网的全面整合营销服务。公司拥有丰富的网站建设和互联网应用系统开发管理经验、成熟的应用系统解决方案、优秀的网站开发工程师团队及专业的网站设计师团队。
代码如下:
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);
以上是“微信公众号中如何实现倒计时的一个功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!