I'm trying to ucreate a timer function that runs in the background of my code and make it so I can use/check the time. What I mean by use/check, I'm trying to make it so I can call upon that timer function and use it as integer.
This is the code I currently have:
def timer():
for endtime in range(0, 15):
print(15 - endtime)
time.sleep(1)
def hall():
timer()
while (timer > 0):
do something
Currently only using print(15 - endtime)
for confirmation it is counting down.
But what the code does now is execute the countdown and that's it, it never touches the while loop. And of course the last issue is I can't set a function to an int. So I'm looking for some way where I can check where the timer is at and use it in that while loop.
The way you do it, you'll going to have to use multithread.
Here is another, simpler approach : On your script beginning, set a
time_start
variable with the number of seconds since the epoch usingtime.time()
Then when you need the number of elapsed seconds, usetime.time() - time_start
:You can put that in a function as well, defining t_start as a global variable.
The problem with your code is that when you run
hall()
, Python first executes the whole oftimer()
(i.e. the wholefor
loop), and then moves on with the rest of the code (it can only do one thing at a time). Thus, by the time it reaches thewhile
loop inhall()
,timer
is already0
.So, you're going to have to do something about that
timer
so that it counts down once, and then it moves on to thedo something
part.Something that you can do is this:
This should work just fine (if you're only executing
hall
15 times), and condenses your code to just one function.Not the cleanest solution, but it will do what you need.