NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to use a timer with SwiftUI

Paul Hudson    @twostraws   

Updated for Xcode 12.5

If you want to run some code regularly, perhaps to make a countdown timer or similar, you should use Timer and the onReceive() modifier.

For example, this code creates a timer publisher that fires every second, updating a label with the current time:

struct ContentView: View {
    @State var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
            .onReceive(timer) { input in
                currentDate = input

It’s important to use .main for the runloop option, because our timer will update the user interface. As for the .common mode, that allows the timer to run alongside other common events – for example, if the text was in a scroll view that was moving.

As you can see, the onReceive() closure gets passed in some input containing the current date. In the code above we assign that straight to currentDate, but you could use it to calculate how much time has passed since a previous date.

If you specifically wanted to create a countdown timer or stopwatch, you should create some state to track how much time remains, then subtract from that when the timer fires.

For example, we could create a countdown timer that shows time remaining in a label, like this:

struct ContentView: View {
    @State var timeRemaining = 10
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
            .onReceive(timer) { _ in
                if timeRemaining > 0 {
                    timeRemaining -= 1
Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.