Timers in Swift
In Swift, timers are used to create repeating tasks to schedule a work with a delay. It is a class which is formerly known as NSTimer. Swift's timer class provides a flexible way to schedule work to happen in future either once or repeatedly.
Let's see how to create repeating and non-repeating timers, using run loops, keeping track of timers, and how you can reduce their energy and power impact.
Creating a Repeating Timer
We can create and start a repeating counter by using the following syntax:
Let's see an example to demonstrate how to create a repeating counter:
In the above example,
In this example, 5 parameters are used to create a timer.
Creating a Nonrepeating Timer
To create a nonrepeating timer, you have to just set the repeats parameter to false. The timer will only fire once and immediately invalidate itself after.
Note: The above code must run in a class context, for example in a view controller class. The fire() function is part of the class, and self refers to the current class instance.
Create a timer using Closure
In the above code, the last parameter block takes a closure. The closure has one parameter timer itself.
Here, the @objc attribute is used because it makes the fire() function available in Objective-C. The Timer class is part of the Objective-C runtime that is the reason we use that @objc attribute.
Difference between Repeating and Nonrepeating Timers
You have to specify whether a timer is repeating or nonrepeating at the time of creation. The main difference between repeating and nonrepeating timer is:
A nonrepeating timer fires once and then invalidates itself automatically, so, it prevents the timer from firing again.
A repeating timer fires and then reschedules itself on the same run loop. A repeating timer always schedules itself based on the scheduled firing time, as opposed to the actual firing time.
For example, if a timer is scheduled to fire at a specific time and every 10 seconds after that, the scheduled firing time will always fall on the original 10-second time intervals, even if the actual firing time gets delayed.