Reputation: 1235
please anyone tell me how to use sleep() for few milliseconds in swift 2.2?
while (true){
print("sleep for 0.002 seconds.")
sleep(0.002) // not working
}
but
while (true){
print("sleep for 2 seconds.")
sleep(2) // working
}
it is working.
Upvotes: 93
Views: 79277
Reputation: 11
For Example Change Button Alpha Value
sender.alpha = 0.5
DispatchQueue.main.asyncAfter(deadline:.now() + 0.2){
sender.alpha = 1.0
}
Upvotes: 0
Reputation: 87914
I think more elegant than usleep
solution in current swift syntax is:
Thread.sleep(forTimeInterval: 0.002)
Upvotes: 25
Reputation: 17544
use func usleep(_: useconds_t) -> Int32
(import Darwin
or Foundation
...)
IMPORTANT: usleep()
takes millionths of a second, so usleep(1000000)
will sleep for 1 sec
Upvotes: 11
Reputation: 5569
DispatchQueue.global(qos: .background).async {
let second: Double = 1000000
usleep(useconds_t(0.002 * second))
print("Active after 0.002 sec, and doesn't block main")
DispatchQueue.main.async{
//do stuff in the main thread here
}
}
Upvotes: 4
Reputation: 5569
DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) {
/*Do something after 0.002 seconds have passed*/
}
Upvotes: 2
Reputation: 8610
usleep() takes millionths of a second
usleep(1000000) //will sleep for 1 second
usleep(2000) //will sleep for .002 seconds
OR
let ms = 1000
usleep(useconds_t(2 * ms)) //will sleep for 2 milliseconds (.002 seconds)
OR
let second: Double = 1000000
usleep(useconds_t(0.002 * second)) //will sleep for 2 milliseconds (.002 seconds)
Upvotes: 160
Reputation: 7537
If you really need to sleep, try usleep
as suggested in @user3441734's answer.
However, you may wish to consider whether sleep is the best option: it is like a pause button, and the app will be frozen and unresponsive while it is running.
You may wish to use NSTimer
.
//Declare the timer
var timer = NSTimer.scheduledTimerWithTimeInterval(0.002, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
self, selector: "update", userInfo: nil, repeats: true)
func update() {
// Code here
}
Upvotes: 4