检查计时器是否正在运行

检查计时器是否正在运行

本文介绍了检查计时器是否正在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用计时器重新填充游戏生命,但是每当我离开视图并返回时,计时器都会重复并变得更快.我试图用 Timer?.isValid 函数解决这个问题,只在计时器无效时运行计时器,因此它永远不会重复,但它似乎无法检查计时器是否无效 在 if 语句中.

I have been trying to refill in game lives with a timer, but whenever I leave a view and return, the timer duplicates and becomes faster. I have tried to address this with the Timer?.isValid function to only run the timer when it is invalid so it never duplicates, but it cannot seem to check is the timer is invalid in an if statement.

这是我迄今为止一直使用的 if 语句:

This is the if statement that I have been using so far:

if (myTimer?.isValid){
} else{
//start timer
}

任何帮助将不胜感激,谢谢.

Any help would be appreciated, thanks.

推荐答案

我推荐使用自检 startTimer()stopTimer() 函数,定时器会仅当它当前未运行时才启动,停止函数将 timer 变量可靠地设置为 nil.

I recommend to use self-checking startTimer() and stopTimer() functions, the timer will be started only if it's not currently running, the stop function sets the timer variable reliably to nil.

var timer : Timer?

func startTimer()
{
    if timer == nil {
        timer = Timer.scheduledTimer...
    }
}

func stopTimer()
{
    if timer != nil {
       timer!.invalidate()
       timer = nil
    }
}

这篇关于检查计时器是否正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:09