Skip to content

Instantly share code, notes, and snippets.

@choefele
Created February 18, 2015 15:41
Show Gist options
  • Save choefele/5e5a981ed731472b80d9 to your computer and use it in GitHub Desktop.
Save choefele/5e5a981ed731472b80d9 to your computer and use it in GitHub Desktop.
Cancellable dispatch block with delay
func dispatch_after_cancellable(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t) -> () -> Void {
var isCancelled = false
dispatch_after(when, queue) {
if !isCancelled {
block()
}
}
return { isCancelled = true }
}
// Usage:
var cancelMessage: () -> Void = {}
cancelMessage()
cancelMessage = dispatch_after_cancellable(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
// do something
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment