【问题标题】:why timer count down irregularly?为什么定时器倒计时不规律?
【发布时间】:2022-01-03 13:17:56
【问题描述】:

我正在为我的父母制作一个计时器应用程序,但它有时会不规律地倒计时......

Count down too fast when set 10 seconds

尤其是在第一次开始并像照片一样恢复时首先计数。

if timer == nil {
        self.timerTime = self.originalTime
        timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timer?.schedule(deadline: .now() + 2, repeating: 1)
        timer?.setEventHandler(handler: {
            if self.timerTime > 0 {
                //timer run
                self.timerTime -= 1
                self.timeCal()
                self.playSound()
                print(self.timerTime)
            } else {
                //timer end
                DispatchQueue.main.async {
                    self.view.backgroundColor = .red
                    AudioServicesPlayAlertSoundWithCompletion(1304, nil)
                }
                self.timeCal()
                
                self.appStat = Stat.loopEnd
                self.timer?.cancel()
                self.timer = nil
            }
        })
    }

这是我的计时器逻辑。 我正在使用 DispatchSourceTimer 以方便恢复。

func updateLabel() {
    DispatchQueue.main.async {
        self.minuteLabel.text = String(format: "%02d", self.minuteCount)
        self.secondLabel.text = String(format: "%02d", self.secondCount)
    }
}

func timeCal() {
    self.minuteCount = self.timerTime / 60
    self.secondCount = self.timerTime % 60
    updateLabel()
}

这是使用的另一种方法。

我已经将计时器的主队列更改为全局,但还是一样...

我想也许这就是为什么许多示例使用 Timer 类的预定计时器的原因。

把dispatchSourceTimer改成Timer类可以解决吗?

如果正确,为什么它们之间会有这种差异?

感谢阅读我蹩脚的英语。 祝你有美好的一天。

【问题讨论】:

    标签: swift timer


    【解决方案1】:

    当您从“设置”屏幕更新持续时间时,您应该尝试使当前运行的计时器无效并使其为零。

    如果有任何疑问,请告诉我。

    【讨论】:

    • 如果我在设置计时器之前运行任何计时器,那就对了。但第一次没有当前正在运行的计时器。 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2020-03-19
    相关资源
    最近更新 更多