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

后端 未结 4 530
無奈伤痛
無奈伤痛 2021-02-02 07:03

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. T

4条回答
  •  星月不相逢
    2021-02-02 07:24

    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
    }
    

提交回复
热议问题