When you close your application, you can use the "Panel Close?" event to ascertain the conditions of closing and decide what are the actions you need to do before closing. When using "Panel Close?", you'll notice that you can choose to discard the event on the right side of your event case. If you choose to discard it, the "Panel Close" event will be filtered out. By doing so, you will handle all the cases required to close your app the way you want and decide which case will effectively stop your loop(s).
Or do you really need the Application Close event?