#10: Executing closures with a delay in Swift 3

There are a few ways to execute a closure with a delay, you could use the old Timer class and its sheduledTimer method or even create a DispatchSource scheduling a one time event with scheduleOneshot, but you can have the same result simply using the Grand Central Dispatch and its queues:


DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
    // Your code that will be executed with a 4 seconds delay
})

Note how after SE-0088 the GCD has now a more “object oriented” interface and how easily you can specify a dealine using DispatchTime and the DispatchTimeInterval enum.

Did you like this article? Let me know on Twitter or subscribe for updates!


I'm also on Twitter and GitHub.

Subscribe via RSS.