Skip to content

Instantly share code, notes, and snippets.

@nixzhu
Last active March 11, 2017 17:10
Show Gist options
  • Save nixzhu/983cedfd05afe9401ba5 to your computer and use it in GitHub Desktop.
Save nixzhu/983cedfd05afe9401ba5 to your computer and use it in GitHub Desktop.
Cancelable Delay Task
import Foundation
typealias CancelableTask = (cancel: Bool) -> Void
func delay(time: NSTimeInterval, work: dispatch_block_t) -> CancelableTask? {
var finalTask: CancelableTask?
var cancelableTask: CancelableTask = { cancel in
if cancel {
finalTask = nil // key
} else {
dispatch_async(dispatch_get_main_queue(), work)
}
}
finalTask = cancelableTask
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
if let task = finalTask {
task(cancel: false)
}
}
return finalTask
}
func cancel(cancelableTask: CancelableTask?) {
cancelableTask?(cancel: true)
}
// test
/*
delay(3) { println("delay 3") }
let cancelableTask = delay(4) { println("delay 4") }
cancel(cancelableTask)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment