Q : Python time
<p>I would like to use Â·time()Â· to launch an event. An example would be to <code>print("test")</code> for 3 seconds. For that I did this: </p>

<pre><code>from time import time, sleep

from random import random

t = time()
n = 3

print(n, time() - t)

for i in range(100):
    sleep(0.04)
    print(time() - t)
    if time() - t &gt; n:
        print("test")
        break 
</code></pre>

<p>and it works! But in my game, in a while loop, it does not work... Why not?</p>

<p>if you want to achieve something else during the 3 second delay period, rather than just going round a while loop, try using a time-delayed thread. For example, the following </p>

<pre><code>import threading
import time

def afterThreeSec():
    print("test")
    return

t1 = threading.Timer(3, afterThreeSec)
t1.setName('t1')
t1.start()

print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
</code></pre>

<p>gives the output:</p>

<pre><code>main
main
main
test
main
main
</code></pre>

python python-2.7 time