Search code examples
iosswiftfunctiondelay

Delaying function in swift


I don't have a code to sample or anything, because I have no idea how to do it, but can someone please tell me how to delay a function with swift for a set amount of time?


Solution

  • You can use GCD (in the example with a 10 second delay):

    Swift 2

    let triggerTime = (Int64(NSEC_PER_SEC) * 10)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
        self.functionToCall()
    })
    

    Swift 3 and Swift 4

    DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
        self.functionToCall()
    })
    

    Swift 5 or Later

     DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
            //call any function
     }