-4

I have doubt for the run thread with time delay Dispatch is not enter to after finished the time?

 for i in 0...10000 {
      let deadLine = DispatchTime.now() + .milliseconds(1000)
      DispatchQueue.main.asyncAfter(deadline: deadLine) {
        print(i)
      }
    }

Anyone have done this before? Thanks.

Manikandan S
  • 115
  • 3
  • 18

1 Answers1

1

The for loop doesn't wait, it is executed in the main thread. DispatchQueue.main.asyncAfter doesn't block the main thread, all it does is queue a block of code to be executed after certain time. Queuing the printing of i is done at almost the same time, maybe spaced in time by a few microseconds if not nanoseconds.

Instead of trying to block the main thread, you could use the Timer API :

//In a playground
var timer: Timer? = nil
var counter = 0

timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
    print("\(counter)\t\(Date())")

    if counter == 10 {
        timer?.invalidate()
    }

    counter += 1
}

timer?.fire()

Which would print for example:

0   2019-08-19 20:19:36 +0000
1   2019-08-19 20:19:37 +0000
2   2019-08-19 20:19:38 +0000
3   2019-08-19 20:19:39 +0000
4   2019-08-19 20:19:40 +0000
5   2019-08-19 20:19:41 +0000
6   2019-08-19 20:19:42 +0000
7   2019-08-19 20:19:43 +0000
8   2019-08-19 20:19:44 +0000
9   2019-08-19 20:19:45 +0000
10  2019-08-19 20:19:46 +0000
ielyamani
  • 17,807
  • 10
  • 55
  • 90