How to Trigger an Action After a Delay in SwiftUI

How to Trigger an Action After a Delay in SwiftUI

Written by

in

Quick answer: Use .task { try? await Task.sleep(nanoseconds: 7_500_000_000); state = true } for Swift 5.5+ or .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 7.5) { state = true } } for older versions. Both update @State after the delay, causing the view to re-render.

Why this happens

SwiftUI views are value types that re-render when their @State or @ObservedObject properties change. There is no built-in “wait” modifier because the view body must return quickly. To run code after a delay you need an asynchronous mechanism that captures the view’s state reference and mutates it later on the main thread. The two standard mechanisms are the modern Task.sleep API (Swift 5.5 / iOS 15+) and the older DispatchQueue.main.asyncAfter closure.

Both approaches schedule work on the main queue so the state mutation is safe for UI updates. The task(_:) modifier automatically cancels the task when the view disappears, preventing stale updates. onAppear + asyncAfter requires manual cancellation if the view can disappear before the deadline fires.

How to fix it

1. Modern async/await with task(_:) (Swift 5.5, iOS 15+)

This is the cleanest API. The task(_:) modifier runs an async closure when the view appears and cancels it on disappear. Inside the closure you suspend with Task.sleep(nanoseconds:) then mutate @State.

import SwiftUI

struct DelayedMessageView: View {
    @State private var hasTimeElapsed = false

    var body: some View {
        Text(hasTimeElapsed ? "Sorry, too late." : "Please enter above.")
            .task(id: hasTimeElapsed) { // re-run if you reset the flag
                do {
                    try await Task.sleep(nanoseconds: 7_500_000_000) // 7.5 s
                    hasTimeElapsed = true
                } catch {
                    // Task was cancelled (view disappeared)
                }
            }
    }
}

Key points
– Task.sleep takes nanoseconds; 1 second = 1_000_000_000.
– Wrap in do/catch because sleep throws CancellationError when the task is cancelled.
– The id: parameter (optional) restarts the task when the value changes, useful for resettable timers.

2. Classic DispatchQueue.main.asyncAfter with onAppear

Use this when targeting iOS 14 or earlier, or when you need to attach the delay to a specific event other than view appearance (e.g., a button tap).

import SwiftUI

struct DelayedMessageView: View {
    @State private var hasTimeElapsed = false

    var body: some View {
        Text(hasTimeElapsed ? "Sorry, too late." : "Please enter above.")
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 7.5) {
                    hasTimeElapsed = true
                }
            }
    }
}

Caveats
– No automatic cancellation. If the view disappears before 7.5 s, the closure still runs and mutates state of a view that is no longer on screen (harmless but wasteful).
– For cancellable work, store the DispatchWorkItem and call .cancel() in .onDisappear.

3. Animation-only delays

If the only goal is to start an animation after a pause, use the built-in .delay on the animation curve instead of mutating state.

.onAppear {
    withAnimation(.spring().delay(0.5)) {
        scale = 1.0
    }
}

This keeps the logic inside the animation system and avoids an extra state variable.

How to prevent it

  • Prefer task(_:) on iOS 15+; it handles cancellation automatically.
  • Always mutate @State on the main actor (both APIs above do this).
  • If you need a repeating timer, use Timer.publish(...).autoconnect() with onReceive instead of chaining sleeps.
  • Avoid Thread.sleep or RunLoop tricks; they block the main thread and freeze the UI.

FAQ

Can I cancel a Task.sleep before it fires?

Yes. The task(_:) modifier cancels the task automatically when the view disappears. If you create a Task manually, call task.cancel() and catch CancellationError in the do/catch block.

Why does my view not update after DispatchQueue.main.asyncAfter?

Ensure the closure captures self (or the @State property) and runs on the main queue. The example above uses DispatchQueue.main, which is correct. If you accidentally used a background queue, wrap the mutation in DispatchQueue.main.async {}.

How do I restart the delay when a value changes?

Add an id: parameter to .task(id: someValue) { … }. When someValue changes, SwiftUI cancels the old task and starts a new one. With onAppear you would need to manage a DispatchWorkItem manually.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.