Skip to content

Instantly share code, notes, and snippets.

@EyreFree
Created July 19, 2017 06:58
Show Gist options
  • Save EyreFree/471356968b87d9c640b883fd5bd81e62 to your computer and use it in GitHub Desktop.
Save EyreFree/471356968b87d9c640b883fd5bd81e62 to your computer and use it in GitHub Desktop.
GCDCancelableDelayCall
import Foundation
class GCDDelayTask: NSObject {
typealias DelayTask = (_ cancel: Bool) -> Void
var pendingTask: DelayTask?
/// 延时执行
func delay(time: TimeInterval, task: @escaping () -> ()) {
func dispatch_later(block: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time, execute: block)
}
var closure: (() -> ())? = task
var result: DelayTask?
let delayedClosure: DelayTask = {
cancel in
if let internalClosure = closure {
if cancel == false {
DispatchQueue.main.async(execute: internalClosure)
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if let delayedClosure = result {
delayedClosure(false)
}
}
pendingTask = result
}
/// 取消待执行的任务
func cancel() {
pendingTask?(true)
}
/// 有待执行的任务
func hasTask() -> Bool {
return nil != pendingTask
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment