Home > OS >  iOS Swift - Prevent Timer #fire() on #invalidate()
iOS Swift - Prevent Timer #fire() on #invalidate()

Time:01-20

Given the following code

private var myTimer: Timer? = nil

override func viewDidLoad() {
   super.viewDidLoad()
   // start my Timer
   startMyTimer()
   
   // stop timer and restart
   DispatchQueue.main.asyncAfter(deadline: .now()   .seconds(3)) {
      self.myTimer!.fire()
      print("my timer: invalidating \(Date.now.mediumTimeLocalizedDescription)")
      self.myTimer!.invalidate()
      self.myTimer = nil
      self.startMyTimer()
   }
}

private func startMyTimer() {
   myTimer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
      print("my timer: Fired \(Date.now.mediumTimeLocalizedDescription)")
   }
   myTimer!.fire()
}

I get the following output:

my timer: Fired 14:27:14
my timer: Fired 14:27:17
my timer: invalidating 14:27:17
my timer: Fired 14:27:17
my timer: Fired 14:27:27

Expected output:

my timer: Fired 14:27:14
my timer: Fired 14:27:17
my timer: invalidating 14:27:17
my timer: Fired 14:27:27

As you can see when I invalidate the timer fires right away!

Is there any way to prevent that?

I looked Apple documentation and it states "Stops the timer from ever firing again and requests its removal from its run loop." which I interpret as "When you invalidate, the timer does not fire anymore". Am I wrong?

CodePudding user response:

You call startMyTimer() again in DispatchQueue.main.asyncAfter completion. In this function you initialize timer.

  • Related