-
Notifications
You must be signed in to change notification settings - Fork 472
Calling a Method After Delay
Charlie Hieger edited this page Sep 28, 2016
·
3 revisions
When prototyping or orchestrating animations, it is sometimes useful to run a method after some delay.
Because the mechanism for using Grand Central Dispatch is a bit ugly, it's useful to wrap it up into a convenient function. Put the function below into each view controller that you want to use it.
func run(after wait: TimeInterval, closure: @escaping () -> Void) {
let queue = DispatchQueue.main
queue.asyncAfter(deadline: DispatchTime.now() + wait, execute: closure)
}
To run code after a delay, simply call the method, as below. Since the code in the braces is a closure, you have to use self
to refer to your class methods and variables.
// Delay for 2 seconds, then run the code between the braces.
let secondsToDelay = 2.0
run(after: secondsToDelay) {
// This code will run after the delay
}