I have a Timer that I want to continuously repeat at a given interval, however the only way I can seem to get the Timer to persist is by adding it to RunLoop.main like below:
let timer = Timer(timeInterval: timeInterval, repeats: true) { (timer) in
blockToFire()
}
RunLoop.main.add(timer, forMode: .commonModes)
I understand that using .commonModes should prevent the timer from missing its cue when a user interacts with the UI, but will the timer cause problems being added to the main run loop? Will there be UI slow downs?
The code you posted is fine. A runloop is associated with a particular thread. Timers are usually run on the main thread/main runloop. As such, they will cause "hiccups" in the main thread if their code takes too long to execute. Don't invoke blocks/selectors who's code takes a long time to run from the main thread/attach them to the main run loop, or you will cause a UI slowdown.
You can also create and run a timer on a background thread. I generally use one of the scheduledTimer()
methods, which creates a timer and adds it to the "current run loop" (which means the run loop for the current thread.)
If you want to run a timer on a different thread, you can call one of the scheduledTimer()
methods from your background thread. However beware that you should not make UIKit calls from a background thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With