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? I just want to add a delay of 1 second, which way should I use?
DispatchQueue.main.asyncAfter
is a GCD method and hence it is better in performance. 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.
Though in your case repeats is false it won't effect flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With