Last active
March 11, 2017 17:10
-
-
Save nixzhu/983cedfd05afe9401ba5 to your computer and use it in GitHub Desktop.
Cancelable Delay Task
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 | |
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