In this article

Scheduled Timer: The Fundamentals Automated Timer with a Preset Menu Tolerance for the timer Timer that includes RunLoop Conclusion

The Ultimate Guide to Timer in Swift

At some point in your Swift work, you'll want to set a timer to delay execution of some code, maybe to allow the user time to deliberate before making a decision. Read on as I spill the beans about timers and how to utilize them effectively.

Time's up To utilize Swift in your program, you'll need to import the Foundations framework, from which it is derived.

import Foundation

The timer functionality in your app is now available for use.

Scheduled Timer: The Fundamentals

The scheduledTimer is the most fundamental use of a timer, requiring just the parameters timeInterval, selection, and repetitions to be specified. The number of seconds since the last function/selector call is stored in the timeInterval. When the timer triggers, it invokes the selector as the function/action to take. Last but not least, repeats is a boolean variable that determines whether or not the timer should be repeated or fired just once.

Declaring a timer as Basic:

//declare blank timer variable
            var timer = Timer()
            //in a function or viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
//new function
@objc func timerAction(){
       print(“timer fired!)
    }

You may have noticed that the function contains a @objc. That's because we need a selector in order to build our timer, and you can't make one without it.

Setting repeats to false ensures the timer will only go off once.

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

When using a selector with a recurring timer, you may terminate the timer at any moment by using the.invalidate method.

//in a function or viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
//new function
@objc func timerAction(){
       print(“timer fired!)
      timer.invalidate()
    }

Automated Timer with a Preset Menu in Swift

It is not always necessary to provide a dedicated function for a timer if it already has a selector declared. Simply follow these steps:

Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
                        print("timer fired!")
                        timer.invalidate()
            }

Having this option gives us the ability to quickly build and control the functions that we want our timer to do. For example, if we want to establish a countdown timer, we can simply describe our timer as follows:

var timeLeft = 10
              Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
                         print("timer fired!")
                        timeLeft -= 1
                        self.timerTextField.text = String(timeLeft)
                        print(timeLeft)
                        if(timeLeft==0){
                                    timer.invalidate()
                        }
               }

Take note that we may utilize variables in our selection; but, if you do want to use a variable, you must first define the variable before you can use it.

Tolerance for the timer

The timer tolerance is the amount of delay that you are willing to accept before the timer goes off. You may be wondering why someone would want their timer to be slightly off. Simply put, the reason for this is because it may increase the amount of power that is used. Keep in mind that your program will have a difficult time maintaining your state, particularly when there is a timer running in the background. By allowing the app to have extra time to correctly execute various types of code, which is enabled by establishing a tolerance, we are able to reduce the amount of energy consumption caused by the application.

To determine the level of tolerance, just define it as:

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

Note: It is essential to keep in mind that tolerance might cause your application to run behind schedule, but it will never execute your code ahead of schedule.

Timer that includes RunLoop

The vast majority of the time, while working with Timers, you will want your timer to continue operating in the background even when you are actively engaged in another task inside the app. On the other hand, a standard Timer will execute in a synchronous manner on your thread. This means that it will only run once all of your other responsibilities have been completed before it will start. Additionally, it only operates on your Main thread, which will halt whenever you start interacting with the user interface (UI).

This is where RunLoop comes into play; RunLoop will assist us in determining where on the thread we want our Timer to execute so that it can perform its work. In our particular scenario, we would want to be able to continue looping the timer even when we are currently engaging with the user interface (UI). As a result, the thread that we are going to put up will be the RunLoop. The "common" input modes are managed by the Mode.common thread, which is the appropriate name for this thread.

Simply inserting the following code into the "common" Runloop will result in the addition of a Timer:

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

Conclusion

Working with timers can be highly satisfying and may add a degree of complexity to your app that is both enjoyable and practical. This level of depth can make your app more user-friendly. However, please use caution! Because an unmonitored timer loop has the potential to be a drain on the battery and a consumer of CPU resources, it may eventually lead to issues.