My DispatchQueue.main.asyncAfter execution block does not wait to execute.
I wrote a MacOS single view app. (xCode 12.0.1 (12A7300)). It has a for-loop that calls a function that downloads content from my server. I want to throttle the requests. I am trying to use DispatchQueue.main.asyncAfter
. But all the calls in the for-loop are made instantly, at the same time. Here is my code:
func fetchDocuments() {
for index in 651...660 {
let docNumber = String(index)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print(Date())
self.fetchDocument(byNumber: docNumber)
}
}
}
When I run this code I get this output on the console:
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
2020-10-05 03:27:09 +0000
I am running this code from Xcode and observing the console.
Any help will be appreciated.