Learn Courses My Dashboard

Real-time timer

I’m making an app to memorize as many digits as possible in a given time. In my MemoryView, I have a count down timer showing time left, Some digits to memorize from an array and two buttons to get to the next or previous digits from the array. When I push the buttons more often than the timer publishes (every second), the timer pauses.


let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

I read in the documentation on apple:

“A timer is not a real-time mechanism. If a timer’s firing time occurs during a long run loop callout or while the run loop is in a mode that isn’t monitoring the timer, the timer doesn’t fire until the next time the run loop checks the timer. Therefore, the actual time at which a timer fires can be significantly later.”

What is the best way to get a “real-time mechanism” timer in this view so that it counts down even if I touch the buttons?

Hello, it should be real time but you need to put the “tick” or trigger on another thread so it doesn’t get interrupted

i suggest checking out our timer article and maybe check out the runloop section

Thank you!

I have problem understanding where to put the

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

Now I have the timer directly in the View, do I put it in the ViewModel and add the

func @objc func timerAction(){
print(“timer fired!”)
}

in the ViewModel also, or directly in the View?

Can I use:


let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

or do I have to use another, like Timer.scheduledTimer?

ViewController with viewDidLoad is an older way to organize the code?