Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode Swift Ios App: Adding delay

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

like image 750
GioB Avatar asked Apr 20 '15 09:04

GioB


People also ask

How do I add a delay in Swift?

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.

How do you delay 2 seconds in Swift?

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.

How do you delay 1 second in Swift?

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.

How do I set timeout in Swift?

“settimeout in swift” Code Answer DispatchQueue. main. asyncAfter(deadline: . now() + 2.0) { // Change `2.0` to the desired number of seconds.


3 Answers

If you only need a sleep function, just use

NSThread.sleepForTimeInterval(1)
like image 118
Nerkyator Avatar answered Sep 20 '22 23:09

Nerkyator


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!

like image 26
TomV Avatar answered Sep 17 '22 23:09

TomV


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

like image 34
Yılmaz Gürsoy Avatar answered Sep 20 '22 23:09

Yılmaz Gürsoy