How to exit a while loop after a certain time?

后端 未结 4 952
灰色年华
灰色年华 2020-12-15 21:54

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){

}
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 22:39

    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

提交回复
热议问题