Search code examples
swiftfoundation

Timer added with scheduledTimer(withTimeInterval works fine with UI interaction


I've scheduled the timer with scheduledTimer(withTimeInterval: 0.008 and it is going on despite the user interaction. This IS the behavior that I want but this article https://www.hackingwithswift.com/articles/117/the-ultimate-guide-to-timer implied that it won't/doesn't work. But it does for me.

This is on iOS 16.1 simulator.

So do I still need runLoop/CADisplayLink mode .common or this somehow works on recent iOSes by .default if you pardon the pun.

Upd: I've resolved this for myself switching to CADisplayLink mode .common since that is more efficient than firing timer 120 times per second anyway but the question still stands why NSTimer fired in .default mode with UI interaction in progress.


Solution

  • According to the docs the scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping @Sendable (Timer) -> Void) -> Timer:

    Creates a timer and schedules it on the current run loop in the default mode.

    So it uses the same run loop as the main thread, if the main thread is busy processing user input events then the timer events will not be executed. To reproduce this you can tap on a tableview and start scrolling, until you lift your finger the timer will not fire. The information from the guide seems to be correct.