Skip to content

Instantly share code, notes, and snippets.

@MortenGregersen
Created May 18, 2024 07:50
Show Gist options
  • Save MortenGregersen/a09567cdf3b7c9c9aac15c50c1f0f002 to your computer and use it in GitHub Desktop.
Save MortenGregersen/a09567cdf3b7c9c9aac15c50c1f0f002 to your computer and use it in GitHub Desktop.
A wrapper around Timer to make it pausable. Only `invalidate` has been exposed, but other functions and properties could be exposed if needed.
import Foundation
public class PausableTimer {
public var isPaused: Bool { remainingTime != nil }
private let timer: Timer
private var remainingTime: TimeInterval?
public static func scheduledTimer(withTimeInterval interval: TimeInterval,
block: @escaping (Timer) -> Void) -> PausableTimer {
PausableTimer(timer: .scheduledTimer(withTimeInterval: interval,
repeats: false,
block: block))
}
private init(timer: Timer) {
self.timer = timer
}
public func pause() {
guard timer.fireDate > Date.now else { return }
remainingTime = timer.fireDate.timeIntervalSince(Date.now)
timer.fireDate = .distantFuture
}
public func resume() {
guard let remainingTime else { return }
timer.fireDate = Date(timeIntervalSinceNow: remainingTime)
self.remainingTime = nil
}
public func invalidate() {
timer.invalidate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment