0

I'm trying to use timeout on python to make a quick time event. The problem arises when I try to change up the code a little bit.

This is the code:

import time
from threading import *
time.sleep(random.randint(1,5))
timeout = 5
#want to replace "you timed out" with function lets say menu.hall()
l = Timer(timeout, print, ["You timed out"] )
l.start()
start_time = time.time()
lol = f"You have {timeout} seconds to dodge, press enter...\n"
answer = input(lol)
l.cancel()
end_time = time.time()
reaction_time = end_time - start_time
if reaction_time < timeout:
   print(f"You dodged in {reaction_time}! ")
   time.sleep(3)
   menu.startp()

I'm trying to replace "you timed out" with a function and the problem rose that the function wouldn't start until it got to the replacement, and then it wouldn't complete the quick time event. What should I do to fix this problem?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Please provide a runnable code. – S.B Oct 07 '22 at 19:33
  • Welcome to Stack Overflow. Hint: the problem with trying to replace "you timed out" with a function is that the existing `Timer` **already uses** a function - `print` - which is what **actually needs** to be replaced with a **different** function. The `["you timed out"]` part is a list of **arguments for** the function that will be called. – Karl Knechtel Oct 07 '22 at 20:16

1 Answers1

0

This is the signature for the Timer.

class threading.Timer(interval, function, args=None, kwargs=None)

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used.

So the function that you want to run when the timer stops is the second positional argument, and the rest are the arguments for that function. So by adding the function where it says "You Timed Out" all you are doing is printing the function instead of "You Timed Out"

Alexander
  • 16,091
  • 5
  • 13
  • 29
  • Thank you very much! I'll be trying this out, sounds a bit complicated but i guess doesnt hurt ot try. – Mareks Zuks Oct 07 '22 at 20:06
  • @MareksZuks this is the class you are already using... What are you expecting to happen by replacing the string with a function? – Alexander Oct 07 '22 at 20:07
  • It's not complicated. The thing that you want to call (in your case, `menu.hall` - no parentheses!), replaces `print`. The *arguments that you want to use* for that call, replace the list. (In your case, because `menu.hall` apparently doesn't need any arguments, this would be an empty list.) – Karl Knechtel Oct 07 '22 at 20:22