Exit from cycle needed

Search the forum for 'state machine'. There have been any number of examples posted (some by me) that illustrate the technique - it's ideal for your application.