I am working on a simple quiz game and i want to add some little delays to the game,now when i select the answer the game goes instantly to the next answer now i want to change the color of the button for 0.1 seconds and then loads the next question
I tried the sleep function but it adds only the delay without the color change and i can't choose time intervals smaller than a second because it accepts integers as value
here is the code
sender.backgroundColor = UIColor.greenColor()
sleep(1)
sender.backgroundColor = UIColor.whiteColor()
what i have to put instead of sleep to obtain what i want?
thanks
Using asyncAfter block in Swift It is a built-in method of Grand central dispatch(GCD) API which helps us to add delay to our code execution in swift. The code that is to be delayed must be placed inside the asyncAfter() block. As a result, the code only executes after the specified time.
To add a delay to your code we need to use GCD . GCD has a built in method called asyncAfter , which will allow us to run code after a given amount of time. In the above code, Before delay will be printed out first and after 2 seconds, Async after 2 seconds will be printed.
Although there's no direct, built-in way to run a Swift Task with a certain amount of delay, we can achieve that behavior by telling the task to sleep for a given number of nanoseconds before we actually start performing its operation: Task { // Delay the task by 1 second: try await Task.
“settimeout in swift” Code Answer DispatchQueue. main. asyncAfter(deadline: . now() + 2.0) { // Change `2.0` to the desired number of seconds.
If you only need a sleep function, just use
NSThread.sleepForTimeInterval(1)
Use usleep which takes an int in microseconds. (i.e. 1,000,000 microseconds is equivalent to 1 second) So for 0.1s use:
// Sleep for 0.1s
usleep(100000)
Recommend to use in a background thread. You certainly don't want to be doing this on the main UI Thread!
You can use NSTimer
for that, firstly you implement NSTimer
and you add duration time 1.0 second or what ever want then, pass the time NSTimer
call its function and you change questions to another
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With