Skip to content

Instantly share code, notes, and snippets.

@macu
Last active February 22, 2022 08:03
Show Gist options
  • Save macu/9a825b53d8b968bd36b8 to your computer and use it in GitHub Desktop.
Save macu/9a825b53d8b968bd36b8 to your computer and use it in GitHub Desktop.
Timeout utility in Swift, with the ability to cancel a deferred callback.
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
}
}
@AdrienGiboire
Copy link

let _ = Timeout(1.0) { self.signin() }

@jasonwiener
Copy link

thanks for sharing this!

@lucas1295santos
Copy link

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