Stop Using Swift Timers: Use CADisplayLink

Hyperbole, but based in truth

Steven Curtis
3 min readOct 28, 2022
Photo by Veri Ivanova on Unsplash

Before we start

Some basic animations, like my loading animation run fine using times to repeat the code blocks and make a UI that looks rather nice to the user.

But this has nothing to do with the framerate of the user’s device, and this may produce a rather horrible drift of the expected animation. In other words, we can do better!

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 12.2, and Swift 5.3

Keywords and Terminology

CADisplayLink: A timer object that allows your application to synchronize its drawing to the refresh rate of the display

The Repo

I’ve prepared a Repo

The theory

A timer isn’t locked to the screen refreshes, and if we think about the standard 60fps that Apple devices tend to work at, we could have a timer fire right after a screen refresh.

In order to do just that, CADisplayLink calls a method that you define when a redraw happens.

We can compare an implementation of a timer updating at 1 / 60 with an implementation…

--

--

Responses (2)