1.延时执行

//延时1秒执行
let time: TimeInterval = 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
//code
print("1 秒后输出")
}

2.对延时执行喵神进行了较好的封装,这里我也贴出来了,供大家学习

import Foundation

typealias Task = (_ cancel : Bool) -> Void

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)
}


/*****使用*****/
//调用
delay(2) { print("2 秒后输出") }



//取消
let task = delay(5) { print("拨打 110") }

// 仔细想一想..
// 还是取消为妙..
cancel(task)

3.OC版本

//延时
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//do something
});