轻量级前端框架助力开发者提升项目效率与性能
1077
2022-10-05
微信公众号开发,实现倒计时的一个功能(纯代码)(微信公众号倒计时怎么做)
以下是我自己编写的一个代码,功能是在微信公众号开发过程中实现倒计时的。效果如下,订单已提交,请在2分57秒内完成支付。纯代码解析。
开始的思路没有考虑页面在后台运行以及锁屏等情况。代码如下:
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);-
apache php mysql
相关文章:
微信公众号授权设置,微信公众授权
相关视频:
传智、黑马微信公众平台开发视频教程
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~