Skip to content

Countdown ​

A wall-clock-difference-driven countdown: no drift across background switches or timer throttling; controlled display and uncontrolled self-advance modes; format tokens DD / HH / mm / ss / S. The instance methods start / pause / reset are exposed via a LhCountdownHandle handle.

Spec source: lh-ui-core/specs/countdown.json · Golden cases: lh-ui-core/cases/countdown.json (10 entries, translated into XCTest, runnable on the macOS host)

Basic usage ​

Uncontrolled mode: pass time (total duration in ms) and autoStart (default true) starts it on mount. The remaining time is computed as "target wall clock − now" and clamped to ≥ 0, without accumulating subtraction — even if the App is suspended in the background and throttled, returning to the foreground corrects it once against the wall-clock difference, with no accumulated drift.

swift
LhCountdown(time: 60_000)                       // Reaches zero after 60 seconds
LhCountdown(time: 3600_000, format: "HH:mm:ss") // 1 hour

Formatting ​

Format-string tokens are case-sensitive: DD (days), HH (hours), mm (minutes), ss (seconds), and S (milliseconds, zero-padded to three digits); other characters render as literals. When DD is absent, HH carries the total number of hours (may exceed 24); negative values clamp to zero.

FormatRemaining 86401500msRemaining 181810000ms
HH:mm:ss (default)00:00:0150:30:10
DD天HH:mm:ss.S01天00:00:01.50002天02:30:10
swift
LhCountdown(value: 86401500, format: "DD天HH:mm:ss.S") // Controlled display: 01天00:00:01.500
LhCountdown(time: 90_000, millisecond: true, format: "ss.S") // Millisecond digit is best refreshed frame-by-frame

Stepping

When millisecond is true, it refreshes frame-by-frame (about 16ms); otherwise it steps every 250ms. If the format string contains the S millisecond token, enabling millisecond is recommended — otherwise the millisecond digit only advances once every 250ms.

Controlled and uncontrolled ​

Passing value makes it controlled: the component does not drive itself and displays the external value (advancing and the finish callback are the caller's responsibility); passing time makes it uncontrolled: with autoStart it runs itself on mount, reporting the remaining milliseconds through onChange on every step, and fires onFinish once when it reaches zero.

swift
@State private var remaining = 3665000

// Note: onChange must be passed explicitly (a trailing closure would bind to the content slot)
LhCountdown(value: remaining, onChange: { remaining = $0 })

Methods and handle ​

LhCountdownHandle exposes start (resumes from the pause point; no effect when disabled) / pause (remembers the remaining time) / reset (returns to the time total duration and can restart per autoStart). Disabling (disabled) grays the component out and pauses the countdown.

swift
@State private var handle = LhCountdownHandle()

LhCountdown(time: 100_000, autoStart: false, handle: handle) {
  LhButton(lhOnClick: { handle.start() }, type: .primary, text: "Start")
}

API ​

Props ​

PropDescriptionTypeDefault
valueRemaining milliseconds (controlled display; once passed, the component does not drive itself)Int?nil
timeUncontrolled total duration (milliseconds)Int0
formatFormat string (DD/HH/mm/ss/S tokens; other characters render as literals)String"HH:mm:ss"
autoStartWhether to start automatically on mount in uncontrolled modeBooltrue
millisecondFrame-by-frame refresh (16ms; otherwise a 250ms step)Boolfalse
disabledDisabled: grays out and pauses the countdownBoolfalse
ariaLabelAccessibility name (falls back to the formatted text when unset)String?nil
handleHandle (start / pause / reset; no effect in controlled mode)LhCountdownHandle?nil
onChangeRemaining-milliseconds change (fired on every uncontrolled step; controlled write-back goes through the same event)((Int) -> Void)?nil
onFinishFired once when the countdown reaches zero(() -> Void)?nil
contentExtra content (default slot, rendered after the digits)@ViewBuilder—

LhCountdownHandle ​

MethodDescription
start()Resumes from the pause point (no effect when disabled or already at zero)
pause()Pauses and remembers the remaining time
reset(time:autoStart:)Returns to the total duration and can restart per autoStart
engineInternal state machine (wall-clock-difference-driven; nil in controlled mode)

Format tokens ​

TokenValue
DDWhole days (when present, HH only carries 0-23)
HHHours; without DD, carries the total number of hours (may exceed 24)
mmMinutes (0-59)
ssSeconds (0-59)
SMilliseconds (0-999, zero-padded to three digits)

Token Reference ​

TokenPurpose
countdown.digitMinWidthMinimum width of digit positions for tabular figures (anti-jitter)
typography.fontSize.baseFont size
typography.fontWeight.primaryFont weight (mapped to Font.Weight on this end)
color.text.primaryDigit text color
color.text.secondarySeparator literal text color (weakened)
color.text.disabledDisabled-state text color

Golden Case Mapping ​

case idAssertionLocal test
renders-formatted-remainingThe controlled value renders as HH:mm:ss with the default formattestRendersFormattedRemaining
negative-clamps-to-zeroNegative values clamp to all zerostestNegativeClampsToZero
hours-over-24-without-ddWithout DD, HH carries the total number of hourstestHoursOver24WithoutDd
dd-format-splits-daysDD splits by days and zero-pads milliseconds to three digitstestDdFormatSplitsDays
uncontrolled-autostart-ticksUncontrolled autoStart runs itself on mount and fires onChangetestUncontrolledAutostartTicks
finish-emits-once-at-zeroReaching zero fires onFinish once and then stops the tickertestFinishEmitsOnceAtZero
controlled-does-not-self-driveControlled mode does not drive itselftestControlledDoesNotSelfDrive
autostart-false-waits-for-startautoStart=false waits for start() to begin countingtestAutostartFalseWaitsForStart
disabled-pauses-and-greysDisabled grays out and stops driving (color.text.disabled)testDisabledPausesAndGreys
aria-role-timerThe accessibility name falls back to the formatted texttestAriaLabelFallbackToFormattedText

Plus dedicated tests: testTokenValuesArePositionalAndZeroPadded / testTokenizeThenRenderMatchesFormat / testEnabledAppearanceUsesTokens / testDarkColorsComeFromDarkTokens / testStepInterval / testResetRestoresTotalAndOptionallyRestarts / testPauseFreezesRemaining / testHandleMethodsOperateEngine / testAttachWithDisabledPausesImmediately / testCountdownViewInitAcceptsControlledValue.

bash
swift test --filter LhCountdownTests    # Runs on the macOS host, no simulator required

lh-ui native bloodline · iOS (Swift + SwiftUI)