在实际编程过程中经常需要一个延时操作的功能,下面进行一个延时2s的操作
非封装写法
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
//your code
}
简单封装
- 代码
public func delayWithTime(_ time: TimeInterval, work: @escaping () -> ()){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time, execute: work)
}
- 用法
delayWithTime(3) {
//your code
}
进一步封装
- 代码
public typealias CancelableTask = ( _ cancel: Bool) -> Void
public func delay( _ time: TimeInterval, work: @escaping () -> ()) -> CancelableTask?{
var finalTask: CancelableTask?
let cancelableTask: CancelableTask = { cancle in
if cancle {
finalTask = nil
} else {
DispatchQueue.main.async(execute: work)
}
}
finalTask = cancelableTask
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
if let task = finalTask {
task(false)
}
}
return finalTask
}
public func cancel(_ cancelableTask: CancelableTask?) {
cancelableTask?(true)
}
- 用法
//延时操作
let task = delay(3) {
//your code
}
//取消延时
delay(1.5) {
cancel(task)
}