3 min readMar 5, 2026
SwiftHow to Use a Timer
Run repeated work on a schedule.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- Adjust the inputs to match your use case.
Copy and paste
import Foundation
var tick = 0
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
tick += 1
print("Tick", tick)
if tick == 3 {
timer.invalidate()
}
}
RunLoop.current.run(until: Date().addingTimeInterval(3.5))Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
