How to sleep for few milliseconds in swift 2.2?

sulabh qg picture sulabh qg · Jun 30, 2016 · Viewed 48.4k times · Source

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.

Answer

Harris picture Harris · Nov 23, 2016

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)