How to sleep for few milliseconds in swift 2.2?

余生长醉 提交于 2019-12-03 00:57:17

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

use func usleep(_: useconds_t) -> Int32 (import Darwin or Foundation ...)

rocket101

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
}

Alternatively:

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

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
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!