How to sleep for few milliseconds in swift 2.2?
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)
How to create a delay in Swift?
Instead of a sleep, which will lock up your program if called from the UI thread, consider using NSTimer
or a dispatch timer.
But, if you really need a delay in the current thread:
do {
sleep(4)
}
This uses the sleep
function from UNIX.
How to thread sleep in swift on linux
You can import sleep
from Glibc
or Darwin
, but better yet, you can use Thread.sleep(forTimeInterval:)
from Foundation
import Foundation
while true {
print("hello")
Thread.sleep(forTimeInterval: 0.1)
}
How to Wait in Objective-C and Swift
You can use
[self performSelector:@selector(changeText:) withObject:text afterDelay:2.0];
or if you want to display it periodically, check the NSTimer
class.
How to make thread sleep for seconds in iOS?
It would be better if you shared what you have done but it here you go.
There are a few options you can go with:
Option 1
// Standard Unix calls
sleep();
usleep();
Some documentation regarding the sleep
function can be found here. You'll find that they are actually C
functions but since Objective-C
is a strict superset of C we can still use the sleep
and usleep
functions.
Option 2
[NSThread sleepForTimeInterval:2.000];//2 seconds
The Apple documentation for this method states:
Sleeps the thread for a given time interval.
Discussion
No run loop processing occurs while the thread is blocked.
Option 3
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
1 * NSEC_PER_SEC),
dispatch_get_main_queue(),
^{
// Do whatever you want here.
});
The Grand Central Dispatch
route is a pretty good way of doing things as well. Here is the Apple Documentation for Grand Central Dispatch which is quite a good read.
There is also this question that might be pretty useful How to Wait in Objective-C
How to interrupt Thread.sleep. Alternatives?
Thread.sleep
is non-cancelable and blocks a thread. And spinning on a RunLoop
is inefficient. That having been said, there are a few alternatives:
Nowadays, to manage dependencies between asynchronous tasks, we would reach for Swift concurrency’s
Task
rather thanOperation
. In Swift concurrency, we haveTask.sleep
, which, unlikeThread.sleep
, is cancelable and does not block the thread.If you want to stay within
OperationQueue
patterns, you would use an asynchronous customOperation
subclass (perhaps theAsynchronousOperation
shown in either here or here), and then you would use a timer. You could use aDispatchSourceTimer
, or aTimer
, orasyncAfter
with a cancelableDispatchWorkItem
. Which you choose really does not matter. The key is to ensure that thecancel
implementation invalidates theTimer
or cancels theDispatchWorkItem
orDispatchSourceTimer
, e.g.:class OneSecondOperation: AsynchronousOperation {
weak var timer: Timer?
override func main() {
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { [weak self] _ in
self?.finish()
}
}
}
override func cancel() {
super.cancel()
timer?.invalidate()
finish()
}
}Note, the pattern whereby you periodically check
isCancelled
only applies if you have an existing loop. E.g., if you are doing some iterative calculation, for example, that is a very reasonable pattern. But if you are just waiting, the idea of introducing a loop merely to checkisCancelled
is inefficient. Instead, set up a timer and implementcancel
method that cancels that timer, as shown above.
Either way, you want implementation that does not block a thread and can be canceled. With Operation
subclass you have to implement that yourself. With Swift concurrency, you get that for free.
How to create a formatter for TimeInterval to print minutes, seconds and milliseconds
I think the way to look at this is that it's a misuse of a date components formatter. This isn't a date of any kind. It's a string consisting of a certain number of minutes, seconds, and milliseconds. Unlike date math, that's a calculation you can perform, and then you are free to present the string however you like.
If you want to use a formatter to help you with user locales and so forth, then you are looking for a measurement formatter (for each of the substrings).
Example (using the new Swift 5.5 formatter notation):
let t1 = Measurement<UnitDuration>(value: 2, unit: .minutes)
let t2 = Measurement<UnitDuration>(value: 4, unit: .seconds)
let t3 = Measurement<UnitDuration>(value: 345, unit: .milliseconds)
let s1 = t1.formatted(.measurement(width: .narrow))
let s2 = t2.formatted(.measurement(width: .narrow))
let s3 = t3.formatted(.measurement(width: .narrow))
let result = "\(s1) \(s2) \(s3)" // "2m 4s 345ms"
Addendum: You say in a comment that you're having trouble deriving the number milliseconds. Here's a possible way. Start with seconds and let the Measurement do the conversion. Then format the resulting value in the formatter. Like this:
let t3 = Measurement<UnitDuration>(value: 0.344657, unit: .seconds)
.converted(to: .milliseconds)
// getting the `0.xxx` from `n.xxx` is easy and not shown here
let s3 = t3.formatted(.measurement(
width: .narrow,
numberFormatStyle: .number.precision(.significantDigits(3))))
You might have to play around a little with the number-formatter part of that, but the point is that a measurement formatter lets you dictate the number format and thus get the truncation / rounding behavior you're after.
Swift 3.0: delay of less than a second
Well, that's quite easy, don't use seconds, use milliseconds:
let deadlineTime = DispatchTime.now() + .milliseconds(300) // 0.3 seconds
Related Topics
Differences Between Ways of Initializing a Dictionary
Swift Implement Literalconvertible Protocol
Parse.Com Pfquery Order by Time (Swift)
Image Disappears When Styling Class to Make a Round Image
How to Display an Image by an API Url? Swift
Unexpected Non-Void Return Value in Void Function Swift 4 Using JSON Serialisation
Swift: How to Get Information for an Application Which Is Not Running
Why Does Function Has Multiple Return Types in Swift
Swift Alamofire Return Value Is Empty
Swift: Can't Edit Properties of Custom Table Cell Programmatically
How to Convert This Date Format in Swift
Decode/Encode Dictionary Keyed by Date
Handle Single Click and Double Click While Updating the View
How to Set Up Multiple Combine Timer Publishers
Updating Switfui View When Coredata Changes