user1094081
user1094081

Reputation:

Multiple timers in a loop

I have an array of characters, eg.

["A","E","I","O","U","Y"]

I should loop this array and, for every character, start a timer. That is: if the current letter is A, A must be printed and last 2 seconds. After A has been printed, we need to print "E" and it should last 3 seconds, "I" one second, "O" four seconds, etc.

I think I should create a new timer for every character, this way:

Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: 
#selector(printCharacter), userInfo: nil, repeats: false)

but I can't do it inside the loop.

I hoped there was a way to build an array of timers and then fire them sequentially, but this is not possible. Any idea?

Upvotes: 1

Views: 234

Answers (1)

Zell B.
Zell B.

Reputation: 10286

You can achieve this using recursion and DispatchQueue only. If you are not familiar with recursion a simple way to understand it's by googling it

A sample code if print duration isn't linear would look like following :

var currentIndex = 0
let charactersArray = ["A","B","C","D"]
let durations : [TimeInterval] = [1.0,2.0,3.0,4.0]

func printCharacter(){

    guard currentIndex < charactersArray.count else { return }

    print(charactersArray[currentIndex])

    DispatchQueue.main.asyncAfter(deadline: .now() + durations[currentIndex], execute: {

        currentIndex = currentIndex + 1

        printCharacter()
    })
}

printCharacter()

where durations array represent time shown for each character

Upvotes: 3

Related Questions