Search code examples
swiftxcodedelay

Delay loop calling animation process


Here is a section of my code where I am trying to delay a function called dropText that drops a name from the top of the screen. I tried using a delay function but it delays then drops them all at once. What am I missing, or is this method just plain wrong? Thanks in advance:

func delay(_ delay:Double, closure:@escaping ()->()) {
    DispatchQueue.main.asyncAfter(
        deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}

//New group choose method
func groupChoose()
{
    //loop through the players
    for x in 0...players - 1{
            //drop the name in from the top of the screen
            delay(2.0) {
            self.dropText(playing[x])
    }
}

Solution

  • This issue is because you are delaying all of them at once! You should try to assign different delay time to each one:

    for x in 1...players {
       //drop the name in from the top of the screen
       delay(2.0 * x) {
       self.dropText(playing[x-1])
    }
    

    Refactored

    Try to not call array elements by index:

    for playing in playing.enumerated() {
    // drop the name in from the top of the screen
    let player = playing.offset + 1
    delay(2.0 * player) {
        self.dropText(playing.element)
    }