在實(shí)際編程過(guò)程中經(jīng)常需要一個(gè)延時(shí)操作的功能,下面進(jìn)行一個(gè)延時(shí)2s的操作
非封裝寫(xiě)法
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
//your code
}
簡(jiǎn)單封裝
- 代碼
public func delayWithTime(_ time: TimeInterval, work: @escaping () -> ()){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time, execute: work)
}
- 用法
delayWithTime(3) {
//your code
}
進(jìn)一步封裝
- 代碼
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)
}
- 用法
//延時(shí)操作
let task = delay(3) {
//your code
}
//取消延時(shí)
delay(1.5) {
cancel(task)
}