How to wait for the end of an animation to do something?

I want to use a simple animation: a blank screen blinking 10 times (with 50 miliseconds visible and 50 miliseconds invisible).

I want to use this animation in different places in my game (when going from one menu to another). So after the animation ends, I want to call different functions, depending on the case.

I made that code for the animation:

function blink_white()
    local state=0
    count=0

    local white_background = display.newRect( 0, 0, width, height )
    
    local function end_animation()
        white_background:removeSelf()
        white_background=nil
    end
    
    local function animate()
        if state==0 then
            white_background.isVisible=false
        else
            white_background.isVisible=true
        end
        
        state=1-state
        count=count+1

        if count==10 then
            endanimation()
        end

    end
    
    timer_animation=timer.performWithDelay( 50, animate, 10)
    
end

It is ok and works alone like I expected.

But I can’t use it in my game correctly.

Imagine I’m in MENU1 (whith only one button - button1). I press the button, the listener is called and I have:

function menu1()

   local background1=display.newImage(“background1.png”, 0, 0)

   local button1=display.newImage(“button1.png”, 0, 0)

   local function button1_click()

      blink_white()

      – remove menu1 components…

      menu2()

      return true

   end

   button1:addEventListener( “tap”, button1_click )

end

In menu2 I have only another button - button2 :

function menu2()

   local background2=display.newImage(“background2.png”, 0, 0)

   local button2=display.newImage(“button1.png”, 0, 0)

   local function button2_click()

      blink_white()

      – remove menu2 components…

      menu1()

      return true

   end

   button2:addEventListener( “tap”, button2_click )

end

So, when I press button1, it really calls the blink_white(), but I can’t see anything because it just create a timer for showing blank screen blinking in the future several times, and calls imediatly the menu2().

If I’m in menu2 and press button2, the same thing occurs, but it’s called menu1… I can’t see animation.

Of course I can call the correct function - menu1() or menu2() - in the end_animation function inside blink_white(), but I have to put blink_whithe() inside menu1() AND inside menu2(). This is only an example, my real game uses many menus, so it is not good.

So I want something that will detect the end of animation, and only after that, it calls the correct function…

How can I do that well while not repeating the animation function in my code?