Home > Software design >  How to temporary pause function execution?
How to temporary pause function execution?

Time:12-02

I want to make very simple animation by going through emoji one by one

func pickingAnimation() {
        for _ in 1...10 {
            currentEmoji.text = randomEmoji().rawValue 
            //currentEmoji - UILabel
            //randomEmoji() generates a random emoji
        }

Is there any function that adds a temporary pause to function execution, so user could see that emoji are changing? Like wait(1) or something?

CodePudding user response:

Use DispatchQueue.main.asyncAfter and a recursive function call.

As a basic example, try this in a playground (and watch the console!):

func printNumbers(current: Int, limit: Int) {
    print(current)
    if current < limit {
        DispatchQueue.main.asyncAfter(deadline: .now()   1) {
            printNumbers(current: current   1, limit: limit)
        }
    }
}
printNumbers(current: 1, limit: 10)

The point is that between the print statements, nothing is happening. We are not waiting, which would be bad (we'd be block the main thread); literally nothing is happening. So if what you do, instead of print, is display something in the interface, it is in fact displayed.

  • Related