Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

iOS Swift – Prevent Timer #fire() on #invalidate()

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading