简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM