js移动端倒计时

手机系统
  1. 安卓_华为:切后台会保留定时器,但是切回来会触发2个定时器一起轮训
  2. IOS_苹果6:切后台立马挂起不再触发定时器,切回来回复定时器
实现思路

障眼法:
原理:监听进入后台时存时间戳,停掉定时器,再进入前台时计算时间差,如果剩余时间大于时间差,则减去时间差,否则复制剩余时间为0;
直接法:
Apple只允许三种情况下App在后台一直执行,音频视频、定位、未知(还有一种没查到),如果是直播、视频播放、地图类的应用可以这样做,但是有些小需求则无需这样;

封装倒计时方法
// 倒计时
startTime(startTime, curTime, duration) { // 开始计时
    if (this.durationTimer) clearInterval(this.durationTimer);
    let entTime = duration * 60 * 1000 - (curTime - startTime); // 剩余时间
    this.durationTimer = setInterval(() => {
        if (entTime < 1000) {
            clearInterval(this.durationTimer);
            this.advanceSubmit(1);
            return;
        };
        entTime = entTime - 1000;
        let th = Math.floor(entTime / (1000 * 60 * 60) % 24);
        let tm = Math.floor(entTime / (1000 * 60) % 60);
        let ts = Math.floor(entTime / 1000 % 60);
        this.countDown = `${th < 10 ? '0' + th : th}:${tm < 10 ? '0' + tm : tm}:${ts < 10 ? '0' + ts : ts}`;
    }, 1000);
},
监听手机切后台
addMonitorProgram() { // 添加监听前台后台
  const pauseFun = () => {
    if (this.backgroundOperation.state === 0) return;
    this.backgroundOperation.state = 0;
    this.handleHeception();
  };
  const resumeFun = () => {
    if (this.backgroundOperation.state === 1) return;
    this.backgroundOperation.state = 1;
    this.handleBackstage();
  };
  document.addEventListener('pause', pauseFun, false); // 从前台切换到后台
  document.addEventListener('resume', resumeFun, false); // 从后台切换到前台
  this.backgroundOperation.pause = pauseFun;
  this.backgroundOperation.resume = resumeFun;
},
removeMonitorProgram() { // 移除监听
  if (this.backgroundOperation.pause) {
    document.removeEventListener('pause', this.backgroundOperation.pause, false);
  }
  if (this.backgroundOperation.resume) {
    document.removeEventListener('resume', this.backgroundOperation.resume, false);
  }
},
  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值