【问题标题】:Prevent the timer from pausing in the background mode防止计时器在后台模式下暂停
【发布时间】:2018-04-25 05:39:17
【问题描述】:

我的 Ionic3 应用程序中有一个计时器。计时器与setInterval 完美运行,但是当我将应用程序关闭到睡眠模式时,计时器停止运行。将我的应用程序再次带到fourground后,计时器继续 - 但他从之前暂停的地方开始。

如果我在后台运行应用程序,如何防止计时器暂停?

我的组件

time: any;

displayTime() {
  this.time = moment().hour(0).minute(0).second(this.counter++).format('HH : mm : ss');
}

startTime() {
  if(this.runClock == null) {
    this.runClock = setInterval(() => {
      this.displayTime();
    },1000)
  }
}

在我的 HTML 中,我调用 {{ time }}

https://ionicframework.com/docs/native/background-mode/ 之类的插件将无法使用,因为 App Store 将拒绝使用此插件的应用。

还有其他想法吗?

【问题讨论】:

  • 这如何解决后台模式的问题?
  • “从暂停的地方开始”是指 moment() 没有返回正确的时间,还是之前的时间出现了短暂的故障?
  • 时间不对,是的。示例:我开始计时 -> 我等到 00:02:30 -> 我在后台关闭应用程序 -> 我等待 5 分钟 -> 我从后台启动应用程序 -> 计时器可能返回 00 :02:41 .....
  • 然后是 00:02:42 和 00:02:43,对吧?

标签: angular cordova typescript momentjs ionic3


【解决方案1】:

由于在后台模式下运行的应用程序可以是rejected in App Store(这是有充分理由的,因为没有人需要一个会无缘无故耗尽电池的应用程序),这应该在不依赖setInterval的情况下完成计数器和后台模式:

startMoment = moment();

displayTime() {
  this.time = moment.utc( moment().diff(this.startMoment) ).format('HH : mm : ss');
}

【讨论】:

  • 哦,非常棒的方法!但是我的计时器没有启动......我的代码:startAt = moment(); 和:if(!this.runClock) { this.runClock = true; this.startAt = moment(); this.time = moment( moment().diff(this.startAt) ).format('HH : mm : ss'); this.content.resize(); } 计时器从“01:00:00”开始显示,并且仍然存在。
  • 问题中的代码假定startTime 方法保持不变。您仍然需要使用 setInterval 每秒更新一次 time
  • 我做到了,柜台现在可以工作了。但是计数器从 01 小时开始。你知道为什么吗?
  • 我猜它没有考虑时区。我通常建议 moment.utc 来避免这种情况。将此添加到答案中。
  • @EstusFlask 先生如何在其中调用函数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多