5

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
J. Doe
  • 12,159
  • 9
  • 60
  • 114

1 Answers1

8

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.

Aditya Srivastava
  • 2,630
  • 2
  • 13
  • 23