Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Swift 3 Stopping a scheduledTimer, Timer continue firing even if timer is nil

Tags:

timer

swift3

We call startTimer function to start a timer. When we wanted to stop it we call stopTimerTest function but after we called stopTimer function the timerTestAction keeps firing. To check the timer condition we used print and print in timerActionTest returns nil.

var timerTest: Timer? = nil  func startTimer () {     timerTest =  Timer.scheduledTimer(         timeInterval: TimeInterval(0.3),         target      : self,         selector    : #selector(ViewController.timerActionTest),         userInfo    : nil,         repeats     : true) }  func timerActionTest() {     print(" timer condition \(timerTest)") }  func stopTimerTest() {     timerTest.invalidate()     timerTest = nil } 
like image 875
Hope Avatar asked Oct 17 '16 08:10

Hope


People also ask

How do I stop a scheduled timer in Swift?

invalidate() is correct for stopping timer.


1 Answers

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 } 
like image 108
Mat Avatar answered Sep 19 '22 21:09

Mat