I am creating a matching card app for children. How do I create a delay function so that the user can see the two cards they have flipped for one second before they flip back to the default card image?
Delay Function
If you don't mind that the app is totally blocked while waiting, the simplest is to use sleep
sleep(1) // To wait fopr 1 second.If you want your app to be able to do other things in the time, you'll have to dispatcg to another thread. But that may be superfluous here.
How do I create a delay function so that the user can see the two cards they have flipped for one second before they flip back to the default card image?
You should use a
Timer for this. You don’t want to use a simple delay function, like
sleep, because that will block your main thread, and blocking the main thread for a long time is a bad idea. And doing the delay in a secondary thread (or via GCD) is likely to cause more problems than it solves.
In the simplest case this will look something like this:
NSLog("start")
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (_) in
NSLog("done")
}Be aware, however, that the timer does not block your app’s UI, and thus you have to be prepared for UI events while the timer is running. For example, if the user hits the ‘close game’ button before the timer fires, what should you do?
Fortunately
Timer has your back here. It actually returns a value that you can store, and then call
invalidate() on to cancel the timer. for example:
var timer: Timer? = nil
func start() {
NSLog("start")
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (_) in
NSLog("done")
}
}
func cancel() {
if let timer = self.timer {
self.timer = nil
timer.invalidate()
}
}Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"