First Method: NSTimer
func myDelayedFunction() {
print("delayed")
}
func myMainFunction() {
let timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "myDelayedFunction", userInfo: nil, repeats: false)
timer.fire()
}
Second Method: performSelector
func myDelayedFunction() {
print("delayed")
}
func myMainFunction() {
performSelector("myDelayedFunction", withObject: self, afterDelay: 10)
}
Third Method: GCD
(useful if you want an anonymous function)
(adapted from this answer)
let delayInSeconds: Int64 = 3
let popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * Int64(NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue()) {
print("Delayed")
}
Fourth Method: sleep
func myMainFunction() {
sleep(10) //This will block whichever thread you're running on.
print("delayed")
}
I tend to use the first method, because I can always invalidate the timer if I need to (calling timer.invalidate
). Each method has its use case, though.