MasterOnce
HomeBlogHow-To
3 min readMar 5, 2026
Swift

How to Use a Timer

Run repeated work on a schedule.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. 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.