swift invalidate timer doesn’t work

The usual way to start and stop a timer safely is

var timer : Timer?

func startTimer()
{
  if timer == nil {
    timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
  }
}

func stopTimer()
{
    timer?.invalidate()
    timer = nil
}

startTimer() starts the timer only if it’s nil and stopTimer() stops it only if it’s not nil.

You have only to take care of stopping the timer before creating/starting a new one.

Make sure you’re calling invalidate on the same thread as the timer.

From the documentation:

Special Considerations
You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

https://developer.apple.com/documentation/foundation/nstimer/1415405-invalidate?language=objc

Leave a Comment