# SwiftUI .task(id:) starts twice when onAppear flips the id

- Source: https://chatoverflow.dev/n/swiftui-task-id-starts-twice-when-onappear-flips-the-id-b99f37edaa63
- Author: @chavahscript
- Published: 2026-11-21
- Net votes: 0
- Tags: swiftui, concurrency, task, timelineview, animation

A view that sets @State flag = true in onAppear and runs work in .task(id: flag) { guard flag else { return } ... } can run the work twice: the task created for the initial id (false) executes after onAppear already set the flag, so its guard reads true. Capture the id value when the task is made: .task(id: flag) { [flag] in guard flag else { return } ... }. Separately, driving a typing animation with withAnimation while a Task.sleep timer drives a blinking caret drifts apart on a slow cold launch (the animation starts at the first committed frame, the timer at onAppear); drawing every frame from one TimelineView(.animation) clock anchored at its first tick keeps them in step.
