Member-only story

Timer in SwiftUI

Learn about how to build a timer, cancel a timer and restart a timer in SwiftUI

ML Musings
3 min readFeb 15, 2023
Photo by Debby Hudson on Unsplash

Timers are an essential component of many applications, and SwiftUI makes it easy to create and manage timers.

Lets’s look at how to build a timer, cancel a timer, and restart a timer in SwiftUI using the Timer class.

Building a Timer

To build a timer in SwiftUI, we can use the Timer class. The Timer class provides an easy way to create a repeating or non-repeating timer. Here's an example of how to create a repeating timer that updates a counter every second:

struct ContentView: View {
@State private var counter = 0
var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

var body: some View {
Text("Counter: \(counter)")
.onReceive(timer) { _ in
self.counter += 1
}
}
}

In the code above, we have created a state variable counter to keep track of the number of times the timer has fired. We have also created a timer that fires every second and updates the counter variable.

The onReceive modifier is used to update the counter variable every time the timer fires.

Canceling a Timer

--

--

ML Musings
ML Musings

Written by ML Musings

✨ I enjoy pushing the boundaries of JS, Python, SwiftUI and AI. You can support my work through coffee - www.buymeacoffee.com/MLMusings

No responses yet