Looks to me like ths issue is the while loop...
A simple if would be better
The script onLoop function runs continuously over and over again, so whiles should be used with caution.
Also, while loops should have multiple breaking options or they can get stuck. Even stopping the script won't work sometimes if you don't check if the script is stopping in the while loop.
If you must use while loops, best to make a special while function with all of the necessary checks that will break out of it if needed. That way you can easily implement while loops.