Created
July 19, 2017 06:58
-
-
Save EyreFree/471356968b87d9c640b883fd5bd81e62 to your computer and use it in GitHub Desktop.
GCDCancelableDelayCall
This file contains hidden or 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 | |
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