Pause A SwiftUI Countdown Without Resetting It
A countdown reaches 2:14. The user taps Pause, changes a setting, and suddenly it reads 2:09. The timer was apparently only paused while nobody looked too closely.
Freezing a timer means saving its remaining duration. It doesn’t mean replacing an automatically updating label with Text(Date.now, format: ...) and hoping that view never redraws.
We’ll build a small countdown with two explicit states: a fixed interval while running, and a fixed duration while paused. Resuming creates a new deadline from the remaining duration. Ordinary view updates create neither.
This example uses iOS 18 or later. Ampersand Softworks’ SystemFormatStyle walkthrough introduces the formatting APIs; here we’ll add pause/resume ownership and tests for the transitions. These are established APIs. The code uses Swift 6.1 or later for the type-level nonisolated declaration, which keeps the model independent of a project’s default actor isolation; verification used Xcode 27.2 and Swift 6.4.2.
Store what the timer means
Subtracting one from a counter every second makes correctness depend on receiving every tick. A deadline lets us calculate the answer whenever we next need it.
The model below accepts an app-selected duration greater than zero and no more than one day. That is the sample’s input contract, not a Foundation limit. Validate user input before constructing it.
Put the following two Swift blocks in one file:
import SwiftUI
nonisolated struct Countdown {
enum Phase: Equatable {
case paused(remaining: TimeInterval)
case running(interval: Range<Date>)
}
let duration: TimeInterval
private(set) var phase: Phase
init(duration: TimeInterval = 300) {
precondition(duration.isFinite && duration > 0 && duration <= 86_400)
self.duration = duration
self.phase = .paused(remaining: duration)
}
func remaining(at date: Date) -> TimeInterval {
switch phase {
case .paused(let remaining):
return remaining
case .running(let interval):
return min(
interval.upperBound.timeIntervalSince(interval.lowerBound),
max(0, interval.upperBound.timeIntervalSince(date))
)
}
}
mutating func resume(at date: Date) {
guard case .paused(let remaining) = phase, remaining > 0 else {
return
}
phase = .running(interval: date..<date.addingTimeInterval(remaining))
}
mutating func pause(at date: Date) {
guard case .running = phase else { return }
phase = .paused(remaining: remaining(at: date))
}
mutating func finish(_ interval: Range<Date>, at date: Date) {
guard phase == .running(interval: interval),
date >= interval.upperBound else { return }
phase = .paused(remaining: 0)
}
mutating func reset() {
phase = .paused(remaining: duration)
}
}
The transition guards matter. Calling resume twice cannot extend a running timer. Calling pause twice cannot subtract the paused time again. Pausing after the deadline records zero; resuming zero does nothing until Reset. The guarded finish operation handles expiry without giving an old interval permission to finish a newer one.
We retain fractional seconds in the model. Rounding belongs to the display, otherwise each pause/resume cycle can quietly donate part of a second to the timer.
This is a wall-clock deadline. If the system clock changes, the remaining duration can change too. The clamp keeps it between zero and the current interval’s duration; it doesn’t make Date monotonic. For measuring elapsed execution time, use the clock distinction in our ContinuousClock article. Don’t use this sample as a trusted deadline for a purchase, exam, or server authorization.
Give the display a live or frozen input
TimeDataSource.currentDate supplies changing dates to a Text view. SystemFormatStyle.Timer formats a bounded interval: a countdown remains at zero after its end.
For the paused display, use a fixed reference date and an interval of the saved length. The reference is just a formatting anchor. It has no relationship to when the user pressed Pause.
struct CountdownDemo: View {
@Environment(\.scenePhase) private var scenePhase
@State private var countdown: Countdown
@State private var showNote = false
init(duration: TimeInterval = 300) {
_countdown = State(initialValue: Countdown(duration: duration))
}
var body: some View {
VStack(spacing: 20) {
switch countdown.phase {
case .paused(let remaining):
let anchor = Date(timeIntervalSinceReferenceDate: 0)
timerText(at: anchor, interval: anchor..<anchor.addingTimeInterval(remaining))
if remaining == 0 {
Text("Finished")
} else {
Button(remaining == countdown.duration ? "Start" : "Resume") {
countdown.resume(at: .now)
}
}
case .running(let interval):
VStack(spacing: 20) {
Text(.currentDate, format: .timer(countingDownIn: interval))
.font(.largeTitle.monospacedDigit())
.accessibilityIdentifier("countdown")
Button("Pause") { countdown.pause(at: .now) }
}
.task(id: interval) {
do {
while true {
try Task.checkCancellation()
let now = Date.now
if now >= interval.upperBound {
countdown.finish(interval, at: now)
return
}
let delay = interval.upperBound.timeIntervalSince(now)
try await Task.sleep(for: .seconds(delay))
}
} catch {
// Leaving this running interval cancels its wait.
}
}
}
Button("Reset") { countdown.reset() }
Toggle("Show timing note", isOn: $showNote)
if showNote {
Text("The deadline follows the system clock. Paused time stays frozen.")
.font(.footnote)
}
}
.buttonStyle(.bordered)
.padding()
.onChange(of: scenePhase) { _, phase in
if phase == .active,
case .running(let interval) = countdown.phase {
countdown.finish(interval, at: .now)
}
}
}
private func timerText(at date: Date, interval: Range<Date>) -> some View {
Text(date, format: .timer(countingDownIn: interval))
.font(.largeTitle.monospacedDigit())
.accessibilityIdentifier("countdown")
}
}
Start and Resume capture the current date inside the button action. The running branch reads the saved interval. Toggling the note, changing the locale, or reevaluating the view doesn’t calculate a new end date.
The note toggle also gives us an easy regression check: pause, wait a few seconds, then toggle it. The displayed duration should remain unchanged.
There’s no repeating Timer and no per-second mutation of @State. The live text handles its own time presentation. The separate view task normally waits once, then rechecks the saved deadline before asking the model to finish that particular interval. If the clock still says it is early, it sleeps for the remaining time again; this is not a per-second polling loop.
Cancellation alone isn’t our ownership check. finish also compares the captured interval with the current one and verifies that its deadline has passed. An old wait cannot finish a reset or newly resumed countdown. The foreground check uses the same guarded operation when the scene becomes active.
This is a cooperative, scheduled update. It may run later than the deadline. Manual system-clock changes were not tested; the sleep and live digits use different time sources, so this sample doesn’t guarantee immediate reconciliation after a clock adjustment.
Zero on screen is not a completion callback
The Stack Overflow question about stopping timer text at zero already has an answer using the iOS 16 Text(timerInterval:) initializer. That initializer also supports pauseTime; the same state policy can back it. You don’t need iOS 18 just to pause or stop at zero. The format-style version here fits a design that uses the same formatter for live and frozen inputs.
Neither formatting API turns the passage of time into a model mutation. Our model can contain a running interval whose end has passed until the explicit finish check runs. Asking remaining(at:) already returns zero. The task or foreground check changes the model to zero remaining, which presents Finished. Neither performs an external completion action, sends a notification, or starts another round.
If the timer finishes while the app is suspended, the retained deadline still tells the view what to show when it returns. It doesn’t wake the app or perform work in the background. Use the appropriate notification or AlarmKit integration (iOS 26 or later) when the product needs an alert outside the app.
Likewise, @State lasts for this view’s identity. Removing the view or terminating the app does not preserve this countdown. Move the model to an appropriate owner for navigation, and persist an explicit running deadline or paused duration if relaunch recovery is required. A paused duration should not become an old deadline during restoration.
Test transitions before watching seconds pass
Fixed dates make most of the important checks instant:
| Operation | Expected result |
|---|---|
| Start 60 seconds at time 100; pause at 112.25 | 47.75 seconds remain |
| Resume at 1,000 | New deadline is 1,047.75 |
| Resume again while running | Deadline stays 1,047.75 |
| Pause again while already paused | Saved duration stays unchanged |
| Pause after the deadline, then resume | Zero stays zero |
| Ask before the running interval starts | Clamp to that interval’s full duration |
| Finish check before its deadline | Keep running |
| Old interval finishes after Reset and Start | New countdown is unchanged |
| Reset | Original duration, paused |
Then test the real display: pause and force a redraw, resume without resetting, wait past zero, reset, and return after the deadline passed while the app was away. Avoid assertions that demand an update at an exact millisecond; rendering is scheduled work.
The standalone Xcode sample includes the exact code above and its verification fixtures. The exact examples compile for an iOS 18 deployment target using Xcode 27.2 / Swift 6.4.2, with both ordinary and MainActor default isolation. Fixed-date model and formatter checks pass, as do five native UI tests in each mode on an iPhone 18 Pro simulator running iOS 27.2. Those checks cover actual note-toggle redraws, pause/resume, expiry/reset, foreground return, and the largest accessibility text size. Older runtimes, physical devices, VoiceOver, and manual system-clock changes were not tested.