delay() 的实现到处都是,下面是一个 Swift 3 版本的,适用于macOS:
public typealias Task = (_ cancel : Bool) -> Void extension CommonUtil { public static func delay(_ after : TimeInterval, task : @escaping ()->()) -> Task? { return delay(after.dispatchTimeInterval, task: task) } /** 异步延迟调用一个闭包. Samples: * ```swift * _ = CommonUtil.delay(.milliseconds(200), task: { * Swift.print("delay 200ms.") * }) * _ = CommonUtil.delay(.microseconds(1_000_000), task: { * Swift.print("delay 1s.") * }) * _ = CommonUtil.delay(.nanoseconds(1_500_000_000), task: { * Swift.print("delay 1.5s.") * }) * ``` */ public static func delay(_ after : DispatchTimeInterval, task : @escaping ()->()) -> Task? { func dispatch_later(block:@escaping ()->()) { DispatchQueue.main.asyncAfter(deadline: .now() + after) { block() } } let closure = task var result: Task? = nil let delayedClosure: Task? = { cancel in if (cancel == false) { DispatchQueue.main.async() { closure() } } //closure = nil result = nil as Task? } result = delayedClosure dispatch_later { if let delayedClosure = result { delayedClosure(false) } } return result; } public static func cancel(task:Task?) { task?(true) } }