0

I want a timer, but I want it to just affect one function, so it can't just be sleep().

For example:

def printSomething():
    print("Something")
def functionWithTheTimer():
    for i in range(0, 5):
        #wait for 1 second
        print("Timer ran out")

Say the first function is called when a button is clicked, and the second function should print something out every second, both should act independently.

If I used sleep(), I couldn't execute the first function within that one second, and that's a problem for me. How do I fix this?

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
zaq
  • 135
  • 5
  • Possible duplicate of [Run certain code every n seconds](https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds) –  Aug 07 '18 at 11:30
  • This could be a duplicate of https://stackoverflow.com/questions/15167334/alternative-to-pythons-time-sleep – Mohl Aug 07 '18 at 11:38

2 Answers2

1

For your timer function, you may want to do something like this:

def functionWithTheTimer():
    for i in reversed(range(1, 6)):
        print(i)
        time.sleep(1)
    print("finished")

This will print the range backwards (like a countdown), one number every second.

EDIT: To run a function during that time, you can just duplicate and shorten the wait time. Example:

def functionWithTheTimer():
    for i in reversed(range(1, 6)):
        print(i)
        time.sleep(0.5)
        YourFunctionHere()
        time.sleep(0.5)
    print("finished")

You can play with the timings a little so you can get your appropriate output.

miike3459
  • 1,431
  • 2
  • 16
  • 32
0

You can use the datetime library like this:

from datetime import datetime

def functionwithtimer():
   start_time = datetime.now()
   # code stuff you have here 
   print("This function took: ", datetime.now() - start_time)
Bese
  • 66
  • 10