I have a while loop that checks for a variable to turn true. The problem is that if that variable dont turn true, it loops forever. Is there a way to make the while loop check for that variable for x seconds and then abandon the loop? This script is runned on a raspberry pi. The while loop is checking if a button has been pressed. If i let the loop be as it is, it will run the loop forever waiting for that button, the modification i want to make is to stop the while loop after 10 seconds or so if the button hasn t been pressed (the variable is still false).
Asked
Active
Viewed 294 times
-4
-
1Yes, there is (at least) a way. Show us the way you have tried. Does it work? – Aug 02 '18 at 14:37
-
1You could use time.time() and check the time each time you go through the loop. If it goes over a certain limit, then just break from the loop – whackamadoodle3000 Aug 02 '18 at 14:39
-
How would the variable change? Is there anything asynchronous involved? Are you using any framework that would make that easier with some existing timeout function? – deceze Aug 02 '18 at 14:39
-
This script is runned on a raspberry pi. The while loop is checking if a button has been pressed. If i let the loop be as it is, it will run the loop forever waiting for that button, the modification i want to make is to stop the while loop after 10 seconds or so if the button hasn t been pressed (the variable is still false). – Shakerry Aug 02 '18 at 14:43
-
Possible duplicate of https://stackoverflow.com/questions/492519/timeout-on-a-function-call – Thierry Lathuille Aug 02 '18 at 14:44
-
Sounds like you might want to look into threading or async? If you want one thing to run a timer and await an action, and the other to do something without a timer active, definitely look into async. – J0hn Aug 02 '18 at 14:57
1 Answers
0
Solved by making a variable with the time now + x seconds then in the while loop will ad a if to check if the now time is less or equal to the variable defined above. If so, break out the while loop.

Shakerry
- 11
- 3