[英]Should I use a unnamed Timer or DispatchasyncAfter to delay something 1 time?
I can delay something in two ways (well maybe there are more ways): 我可以通过两种方式推迟一些事情(也许还有更多方法):
func delay(delay:Double, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
//way 1:
delay(delay: 1.0, closure: {
})
//way 2:
_ = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false){ _ in
}
Is there any difference between those ways? 这些方式之间有什么区别吗? Is way 1 better than way 2?
方式1比方式2更好吗? I just want to add a delay of 1 second, which way should I use?
我只想添加1秒的延迟,我应该使用哪种方式?
DispatchQueue.main.asyncAfter
is a GCD method and hence it is better in performance. DispatchQueue.main.asyncAfter
是一个GCD方法,因此性能更好。 Though NSTimer
is a much more flexible where you can stop or pause the timer but I don't think you can cancel the DispatchQueue.main.asyncAfter
or at least you have to write a wrapper. 虽然
NSTimer
更灵活,你可以停止或暂停计时器,但我不认为你可以取消DispatchQueue.main.asyncAfter
或者至少你必须编写一个包装器。
Though in your case repeats is false it won't effect flexibility. 虽然在你的情况下重复是错误的,但它不会影响灵活性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.