Detect if user hits Stop
You can use a try block like this:

repeat -- your loop
    try
        --
        -- your code in the loop
        --
    on error err number n
        if n = -128 then -- User canceled
            --
            -- code to  cleanup before the program closes
            --
            return -- exit this script
        end if
    end try
end repeat