1

I can not invalidate a Swift Timer.

When defining my objects and variables I declare the timer with

var scoreTimer = Timer()

I start the timer when two objects collide with this line:

scoreTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(updatePassengerScore), userInfo: nil, repeats: true)

My updatePassengerScore method looks like this

    passengerScore -= 1
    scoreLabel.text = String(passengerScore)

When another collision is detected, I try to stop the timer with

scoreTimer.invalidate()

but the variable passengerScore is still decreasing and I do not have a clue why this is the case. Does anyone have a clue hoe to solve this and make the Timer stop? Every Thread I read says that scoreTimer.invalidate() should actually stop the timer. I am really confused :-/

boehmatron
  • 713
  • 5
  • 15

1 Answers1

2

You might be starting multiple timers. If you hit the line of code that creates a timer before the current one has been invalidated, then you will have two active timers, only one of which you can invalidate.

To prevent this possibility, call invalidate on scoreTimer before creating a new timer:

scoreTimer.invalidate()
scoreTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(updatePassengerScore), userInfo: nil, repeats: true)

The other way to handle it is to change scoreTimer to an optional, and then only create a timer if scoreTimer is nil.

var scoreTimer: Timer?

...

if scoreTimer == nil {
    scoreTimer = Timer.scheduledTimer(...
}

...

scoreTimer?.invalidate()
scoreTimer = nil
vacawama
  • 150,663
  • 30
  • 266
  • 294