Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Timer is running

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.

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

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

Any help would be appreciated, thanks.

like image 708
Jack Sullivan Avatar asked Jun 07 '17 22:06

Jack Sullivan


2 Answers

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
    }
}
like image 119
vadian Avatar answered Oct 13 '22 17:10

vadian


You need to check if your Timer instance isValid (not the Timer class), let's say: if myTimer.isValid? {}.

like image 27
Matias Jurfest Avatar answered Oct 13 '22 16:10

Matias Jurfest