Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? I just want to add a delay of 1 second, which way should I use?

like image 471
J. Doe Avatar asked Aug 12 '17 17:08

J. Doe


1 Answers

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.

like image 67
Aditya Srivastava Avatar answered Nov 15 '22 08:11

Aditya Srivastava