Created
May 18, 2024 07:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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