I have a program to stop the for loop, even though the loop is running. I want to exit from this loop once my timer is over.
Ex: Timer set to = 10 seconds
def Start_function():
timer = 10 seconds
for i in range(60):
print(i)
time.sleep(1)
return
Here loop will continue executing till for loop completion. But I need to exit from this function once the time is reached 10 seconds.
please help me out on this program.
Thanks in advance.
Find the below program:
import threading import time def demo(): print("Start function\n") for i in range(60): print(i, end=" ") time.sleep(1) def thread_cancel(): time.sleep(5)
timer.cancel()
print("Yes ") timer = threading.Timer(1, gfg) timer.start() print("Cancelling timer\n") thread_cancel() print("Exit\n")
>Solution :
You can simply add an if condition to check if i == timer: and then return to terminate the program.
import time
def Start_function():
timer = 10
for i in range(60):
if i == timer:
return "Timer ran successfully"
print(i)
time.sleep(1)
Output:
0
1
2
3
4
5
6
7
8
9
'Timer ran successfully'
But this is a bad implementation of a timer. You can improve by:
def Start_function(timer):
for i in range(timer):
time.sleep(1)
print(i)
Start_function(10) # This starts the timer for 10 second