Skip to content

Instantly share code, notes, and snippets.

@dreymonde
Last active July 17, 2023 20:45
Show Gist options
  • Save dreymonde/7538c4ac708bafc6d2e743a14ceedd4a to your computer and use it in GitHub Desktop.
Save dreymonde/7538c4ac708bafc6d2e743a14ceedd4a to your computer and use it in GitHub Desktop.
"Timers" helper class for Swift with automatic memory management and intuitive API
public final class Timers {
private var timers: [Foundation.Timer] = []
public init() { }
public func clear() {
for timer in timers {
timer.invalidate()
}
timers = []
}
deinit {
clear()
}
internal func addTimerManually(
runLoop: RunLoop = .main,
runLoopMode: RunLoop.Mode = .common,
timer: Timer
) {
runLoop.add(timer, forMode: runLoopMode)
timers.append(timer)
}
public func addRepeating<TargetType: AnyObject>(
timeInterval: TimeInterval,
tolerance: TimeInterval = 0,
withTarget target: TargetType,
handler: @escaping (TargetType, Timer) -> Void
) {
let newTimer = Timer(timeInterval: timeInterval, repeats: true) { [weak target] timer in
if let target {
handler(target, timer)
}
}
newTimer.tolerance = tolerance
addTimerManually(timer: newTimer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment