Table of contents
1.
Introduction
2.
Scheduled Timer
2.1.
Example of the Basic Timer
3.
Creating Repeating Timer
4.
Creating a Non-repeating Timer
5.
Difference between Repeating and Nonrepeating Timers
6.
Creating a Timer Using Closure
7.
Timer Tolerance
8.
Timer with RunLoop
9.
FAQs
9.1.
What are timers in swift?
9.2.
How to reset a timer is swift?
9.3.
What is RunLoop in swift?
10.
Conclusion
Last Updated: Mar 27, 2024

Timers in Swift

Author soham Medewar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Timers are used in Swift to establish repeated tasks to schedule some work with a delay. It is a class that was previously known as NSTimer. Swift's timer class offers a versatile approach to scheduling work to occur in the future, either once or periodically.

Scheduled Timer

The scheduledTimer is the most basic usage for a timer, and it requires you to configure the timeInterval, selector, and repeats. The timeInterval parameter specifies how many seconds have passed since the function/selector was called. When the timer fires, the selector executes the function/action. Finally, the repeats is a boolean variable that determines whether or not the timer should be repeated.

Example of the Basic Timer

var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
@objc func timerAction(){
      print("timer fired!")
    }

Take note of the @objc in the function. This is due to the fact that it is required to build a selector, which is required for our timer.

To force the timer to fire only once, set the option repeats to false.

We'll also look at how to make repeating and non-repeating timers, how to use run loops, how to keep track of timers, and how to limit their energy and power use.

Creating Repeating Timer

Using the following syntax, we can build and start a repeating counter.

Code

let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fire), userInfo: nil, repeats: true)  
@objc func fire()   
{  
    print("Firing the function after specific interval")
} 

In the above example,

  • The Timer.scheduledTimer(...) class method is used to create a timer. This method's return value is allocated to the constant timer. This constant now includes a timer reference, which will be used later.
  • The timer interval is set to 5 seconds in the scheduledTimer() parameters. It uses the target-action mechanism, some nil userInfo, and the parameter repeats set to true.
  • We've also written a function called fire(). This is the function that is called whenever the timer is triggered, which is roughly every second. Setting the target to self and the selector to #selector(fire) indicates that whenever the timer fires, the function fire() of self must be invoked.

The parameters that are used in the above example are

  • timeInterval: It provides the time interval between timer fires in seconds and is of type Double.
  • target: It defines a class instance on which the selector function should be called.
  • selector: It specifies the function to call when the timer fires, with #selector(...)
  • userInfo: It specifies a dictionary containing data supplied by the selection or nil.
  • repeats: It defines whether this timer will repeat or not.

Creating a Non-repeating Timer

To make a non-repeating timer, simply set the repeats option to false. The timer will only fire once and then invalidate itself.

Code

let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fire), userInfo: nil, repeats: false)
@objc func fire()   
{  
    print("Firing the function after specific interval")
} 

Difference between Repeating and Nonrepeating Timers

At the time of creation, you must select whether a timer is repeating or not. The primary difference between a repeating and a non-repeating timer is

A non-repeating timer fire once and then automatically invalidates itself, preventing the timer from firing again.

A timer that repeats itself fires and then reschedules itself on the same run loop. A repeating timer is always scheduled based on the scheduled firing time rather than the actual firing time.

For example, if a timer is set to fire at a given time and then every 10 seconds thereafter, the scheduled firing time will always fall inside the initial 10-second time intervals, even if the actual firing time is delayed.

Creating a Timer Using Closure

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in  
    print("Firing the function using closure")  
})

The last parameter block in the preceding code accepts a closure. The closure has a single parameter timer.

Timer Tolerance

Timer tolerance is set when you are willing to accept a little delayed timer fire. Why would you want your timer to be a little late, you might wonder? Simply said, it is because it can increase power usage. Remember that your programme will struggle to manage your state, especially if a timer is running in the background. By specifying a tolerance, we give the app additional time to properly execute various types of code, which reduces your app's energy consumption.

Define the function in the following way to set tolerance.

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        timer.tolerance = 0.5

Timer with RunLoop

Most of the time, when using Timers, you want your timer to run in the background while you work on another programme. A regular Timer, on the other hand, will execute on your thread synchronously. That is, it will execute only after you have completed all of your other chores. It also only runs in your Main thread, which pauses when you interact with the UI.

This is where RunLoop comes in; RunLoop will assist us in determining where on the thread we want our Timer to execute. In our scenario, we want to be able to loop the timer while interacting with the UI. As a result, the thread we'll be creating will be the RunLoop. The thread that handles "common" input modes is Mode.common.

Simply enter the following lines to add a Timer to the "common" Runloop:

RunLoop.current.add(timer, forMode: RunLoop.Mode.common)

FAQs

What are timers in swift?

Swift's Timer class is a flexible way to schedule work to happen in the future, either just once or repeatedly.

How to reset a timer is swift?

Timer instances are not paused or resumed. We put a stop to them with invalidate(),  and to restart it, simply establish a new timer.

What is RunLoop in swift?

A RunLoop is a programmatic interface to objects that manage input sources for an application, such as touches. The system creates and manages RunLoops, as well as constructs a RunLoop object for each thread object.

Conclusion

In this article, we have covered the following topics:

  • Creating repeating timers
  • Creating non-repeating timers
  • The difference between repeating and non-repeating timers
  • Timer tolerance and timers with RunLoop

Want to learn more about web development or android development? Here is an amazing course for both by coding ninjas.

Happy Learning!

Live masterclass