I have a while loop and I want it to exit after some time has elapsed.
For example:
while(condition and 10 sec has not passed){
}
Proposed and accepted solutions won't do the trick.
It won't stop the loop after 10 seconds. Imagine the code in your loop takes 20 seconds to process and is called at 9.9 seconds. Your code would exit after 29.9 seconds of execution.
If you want to exactly stop after 10 seconds, you have to execute your code in an external thread that you will kill after a certain timeout.
Existing solutions have already been proposed here and there