Last active
February 22, 2022 08:03
-
-
Save macu/9a825b53d8b968bd36b8 to your computer and use it in GitHub Desktop.
Timeout utility in Swift, with the ability to cancel a deferred callback.
This file contains 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 | |
/// Timeout wrapps a callback deferral that may be cancelled. | |
/// | |
/// Usage: | |
/// Timeout(1.0) { println("1 second has passed.") } | |
/// | |
class Timeout: NSObject | |
{ | |
private var timer: NSTimer? | |
private var callback: (Void -> Void)? | |
init(_ delaySeconds: Double, _ callback: Void -> Void) | |
{ | |
super.init() | |
self.callback = callback | |
self.timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(delaySeconds), | |
target: self, selector: "invoke", userInfo: nil, repeats: false) | |
} | |
func invoke() | |
{ | |
self.callback?() | |
// Discard callback and timer. | |
self.callback = nil | |
self.timer = nil | |
} | |
func cancel() | |
{ | |
self.timer?.invalidate() | |
self.timer = nil | |
} | |
} |
thanks for sharing this!
I updated this wrapper
import Foundation
/// Timeout wrapps a callback deferral that may be cancelled.
///
/// Usage:
/// Timeout(1.0) { println("1 second has passed.") }
///
class TimeoutHandler: NSObject {
private var timer: Timer?
private var callback: (() -> Void)?
init(_ delaySeconds: TimeInterval, _ callback: @escaping () -> Void) {
super.init()
self.callback = callback
self.timer = Timer.scheduledTimer(
timeInterval: TimeInterval(delaySeconds),
target: self,
selector: #selector(invoke),
userInfo: nil,
repeats: false
)
}
@objc func invoke() {
self.callback?()
self.callback = nil
self.timer = nil
}
func cancel() {
self.timer?.invalidate()
self.timer = nil
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
let _ = Timeout(1.0) { self.signin() }