Using Swift 3 Stopping a scheduledTimer, Timer continue firing even if timer is nil
Try to make the following changes to your code:
First, you have to change the way you declare timerTest
var timerTest : Timer?
then in startTimer
before instantiating check if timerTest
is nil
func startTimer () {
guard timerTest == nil else { return }
timerTest = Timer.scheduledTimer(
timeInterval: TimeInterval(0.3),
target : self,
selector : #selector(ViewController.timerActionTest),
userInfo : nil,
repeats : true)
}
Finally in your stopTimerTest
you invalidate timerTest
if it isn't nil
func stopTimerTest() {
timerTest?.invalidate()
timerTest = nil
}
Most likely you've called startTimer
twice without calling stopTimerTest
. If you do that, you'll lose your pointer to the original timer and never be able to invalidate it.
The typical approach is to manage invalidation as a part of setting:
var timerTest : Timer? = nil {
willSet {
timerTest?.invalidate()
}
}
Then stopping is just setting to nil:
func stopTimerTest() {
timerTest = nil
}
Make sure when you call StartTimer
it is nil
and if you call StartTimer
twice without calling StopTimer
. You will lose your original pointer and you can't stop it.
var timer : Timer? = nil {
willSet {
timer?.invalidate()
}
}
Start and Stop timer like ...
func startTimer() {
stopTimer()
guard self.timer == nil else { return }
self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.fetchData), userInfo: nil, repeats: true)
}
func stopTimer() {
guard timer != nil else { return }
timer?.invalidate()
timer = nil
}