问题
I've got a code which must be executed every half a second and I'm using the Xcode playground. I used this top answer and got a code like this:
for (index, item) in array.enumerated() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(index), execute: {
print("\(index) - \(df.string(from: Date()))"
//play sound every second
})
}
This code is executed every second (I know that I have to divide it by 2 to get half a second but wanted to see the results). I used the DateFormatter
to figure out times because I couldn't figure out why sounds are not played evenly.
let df = DateFormatter()
df.dateFormat = "ss.SSSS"
The result is that it is not triggered exactly every 1 second.
0 - 17.4800
1 - 18.5770 // even though it's not called exactly after 1s it's acceptable
2 - 19.6750
3 - 20.7770
4 - 21.8780
5 - 22.9760
6 - 24.0710
7 - 25.1690
8 - 26.2720
9 - 27.3640
10 - 28.4760
11 - 28.7580 //0.3s of difference
12 - 30.4800
13 - 30.5060 // 0.1s of difference
14 - 32.4800
15 - 32.5030 // less than 0.1s of difference
回答1:
Here you execute your Print
statement asynchronous so you do not get your printed data after half a second(or one second).If you execute it synchronously then you get your printed data 1 second interval.To know more about dispatch queue follow this link.Let me know if you have any problem.
来源:https://stackoverflow.com/questions/49347450/discrepancies-in-time-when-using-dispatchqueue-in-swift