87

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.

sulabh qg
  • 1,155
  • 2
  • 12
  • 20
  • 1
    Thread sleep or yield is valid in the case of polling, for one. Many interfaces do not offer notifications so you must check every so often for an asynchronous change that is imminent. To do this without pausing the thread between checks will needlessly harass the CPU and probably block the process you are waiting for. – absmiths Nov 18 '16 at 17:57
  • 1
    sleep() takes **int** as parameter. So sleep(0.002) will sleep 0 seconds. Use usleep(nanoseconds) instead – Mark Berner Feb 13 '17 at 09:24
  • For those wanting to use Swift 5.5's async & await sleep, see [this](https://stackoverflow.com/a/68715267/9607863) answer from a different post. – George Aug 26 '21 at 09:53

7 Answers7

153

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)
Elijah
  • 8,381
  • 2
  • 55
  • 49
19

I think more elegant than usleep solution in current swift syntax is:

Thread.sleep(forTimeInterval: 0.002)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • Does `sleep(forTimeInterval:)` just call `nanosleep()`? – ma11hew28 Jan 09 '22 at 02:09
  • 1
    These functions are from different API layers: `nanosleep` is a system function, part of `Darwin`, and `Thread` is part of `Foundation`. It may happen that in the older versions of iOS/macOS it was using `usleep` under the hood, and now it may be using `nanosleep`. Anyway you don't need to use `nanosleep` when you can import `Foundation`, it may only be needed for other languages which cannot use `Foundation`, but still have access to `Darwin`, as it's written in C. – Phil Dukhov Jan 09 '22 at 02:30
  • OK, thank you. :-) – ma11hew28 Jan 09 '22 at 02:36
10

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

ScottyBlades
  • 12,189
  • 5
  • 77
  • 85
user3441734
  • 16,722
  • 2
  • 40
  • 59
4

If you really need to sleep, try usleepas 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
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
rocket101
  • 7,369
  • 11
  • 45
  • 64
  • sometimes it is a good idea to 'pause' some background task for a while ... and sleep and usleep could be very helpful, easy to adopt and inexpensive solution. unfortunately, is is very rarely to see the proper using of sleep or usleep. generally, it is better to avoid it :-) – user3441734 Jul 04 '16 at 16:24
  • It would only freeze the app if you paused the event thread, which is always a terrible idea. Work other than UI should be done off that thread anyway. Normal usage of usleep only causes the current thread to block. – absmiths Nov 18 '16 at 17:59
  • Eh, it's most likely a bad sign if you're calling `usleep` in a high-level part of your app. It can block GCD queues, for one. Only use if the abstractions Apple provides _really_ aren't suitable for what you need to do. – sudo Nov 01 '17 at 20:12
4

Non-blocking solution for usleep:

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
    }
}
Sentry.co
  • 5,355
  • 43
  • 38
2

Alternatively:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) {
   /*Do something after 0.002 seconds have passed*/
}
Sentry.co
  • 5,355
  • 43
  • 38
  • I didn't go deep how does it work but it seems in objective-C (and in Swift) this code produces a new thread each `dTime` without of destroying previous threads. So in better case you waste device's memory, in worst case the app falls due to huge memory consumption (depends on loop count) – Vyachaslav Gerchicov Mar 02 '20 at 14:43
0

For Example Change Button Alpha Value

 sender.alpha = 0.5
 
 DispatchQueue.main.asyncAfter(deadline:.now() + 0.2){
             sender.alpha = 1.0
         }
ugurpolat
  • 1
  • 2