swift invalidate timer doesn't work swift invalidate timer doesn't work ios ios

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(){  if timer != nil {    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.


Something that's not really covered by the previous answers is that you should be careful your timer isn't scheduled multiple times.

If you schedule a timer multiple times without first invalidating it, it'll end up scheduled on multiple run loops, and invalidating it then becomes nigh impossible.

For me, it happened when calling my scheduleTimer() function in separate functions in my view controller's life cycle (viewWillAppear, viewDidAppear, ...)

So in short, if you aren't sure (or you cannot guarantee) your Timer is only scheduled once, just always invalidate it first.