// GCD 和延时调用
DispatchQueue.global().async {
print("耗时的。。。努力工作")
//
DispatchQueue.main.async {
print("结束工作,更新 UI")
}
}
/*
要实现以下功能
delay(2){
print("2秒输出")
}
想取消的话,保留一个 task 的引用,然后调用 cancel
let task = delay(5) {
print("拨打110")
}
仔细想了想,还是取消为妙
cancel(task)
*/
typealias Task = (_ cancel: Bool) -> Void
// 延时执行一个block, 返回这个一个可以取消的block
func delay(_ time : TimeInterval, task:@escaping()->()) -> Task? {
func dispatch_later(block: @escaping()->()){
let t = DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: t, execute: block)
}
var closure:(()->Void)? = task
var result : Task?
let delayedClosure: Task = {
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)
}
}
return result
}
func cancel(_ task: Task?){
task?(true)
}
let task = delay(5) {
print("拨打110")
}
cancel(task)