Zoltan Zoltan - 7 months ago 30
Swift Question

Swift delay in loop

I have this delay function:

func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}


From here:
dispatch_after - GCD in swift?

This code:

func start(){
for index in 1...3 {
delay(3.0){
println(index)
}
}
}


After 3 sec, it gives:


3

3

3


My Goal:


After 3 sec: 1

After 6 sec: 2

After 9 sec: 3


How whould I achieve this?
Thank You,

The problem was I used another type of for loop:

func start(){
for var index = 0; index < 3; index++ {
delay(3.0){
println(index)
}
}
}


As suggested @Shubhank this works as expected:

func start(){
for index in 1...3 {
delay(3.0 * Double(index)){
println(index)
}
}
}


However to use the other kind of for loop I needed @mz2 solution:

func start(){
for var index = 0; index < 3; index++ {
let i = index
delay(3.0 * Double(i+1)){
println(i+1)
}
}
}

Answer

try multiplying delay with index

func start(){
   for index in 1...3 {
      delay(3.0 * index){
         println(index)
      }
   }
}