13

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.

Matias Jurfest
  • 1,378
  • 16
  • 25
Jack Sullivan
  • 199
  • 1
  • 1
  • 10
  • Are you starting the timer in `viewWillAppear`? More info will be helpful. – Mike Jun 07 '17 at 22:17
  • Reallocating a timer or setting it to nil will not invalidate it. Set up the timer once (in 'viewDidLoad' for example) and then invalidate it when you don't need it. – FryAnEgg Jun 07 '17 at 22:34
  • You should deactivate your timer when u leave your view e.g. use in viewWillDisappear `myTimer?.invalidate()` – corban Mar 08 '22 at 14:13

2 Answers2

12

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
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 2
    im not sure if you understand, i want to check if a timer is running, not start/stop a timer – Jack Sullivan Jun 09 '17 at 20:13
  • Your code in the question implies: *If the timer is not valid (is not running), start it*. That's exactly what `startTimer()` does. In my suggested logic the timer is not running if it's `nil`. – vadian Jun 09 '17 at 20:17
  • Sorry, I understand now and your function is working! – Jack Sullivan Jun 09 '17 at 21:30
4

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

Matias Jurfest
  • 1,378
  • 16
  • 25