94

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.

3
  • 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. Commented Nov 18, 2016 at 17:57
  • 2
    sleep() takes int as parameter. So sleep(0.002) will sleep 0 seconds. Use usleep(nanoseconds) instead Commented Feb 13, 2017 at 9:24
  • For those wanting to use Swift 5.5's async & await sleep, see this answer from a different post. Commented Aug 26, 2021 at 9:53

7 Answers 7

161

UPDATE: For Swift 5.5 and later, you can use this

let seconds = UInt64(2)
print("paused at \(Date())")
Task {
    do {
        try await Task.sleep(nanoseconds: seconds * 1_000_000_000)
        print("started again at \(Date()) after \(seconds) seconds")
    } catch {
        print("An error occurred: \(error.localizedDescription)")
    }
}

----------------------------------------------------------------

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)
Sign up to request clarification or add additional context in comments.

2 Comments

UInt32(0.002) is 0. It should read usleep(UInt32(0.002 * second))
man sleep on macOS 11.6 says: "The usleep() function is obsolescent. Use nanosleep(2) instead."
26

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

Thread.sleep(forTimeInterval: 0.002)

2 Comments

Does sleep(forTimeInterval:) just call nanosleep()?
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.
11

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

2 Comments

usleep() takes millionths of a second, so usleep(1000000) will sleep for 1 sec
This ^ this ^ this ^
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
}

3 Comments

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 :-)
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.
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.
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
    }
}

Comments

2

Alternatively:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) {
   /*Do something after 0.002 seconds have passed*/
}

1 Comment

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)
0

For Example Change Button Alpha Value

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.