Quit if idle for X time, problem when saved script as app
I think this is what you're looking for: https://stackoverflow.com/questions/38530412/exit-infinite-loop-by-quitting-application#38531544

More info from Apple: https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/conceptual/ASLR_about_handlers.html#//apple_ref/doc/uid/TP40000983-CH206-SW7

And another reference: https://scriptingosx.com/tag/idle/

Basically, instead of your repeat, you want to do an on idle, instead of the repeat