user3211337
user3211337

Reputation: 85

Python Delay on Loop

I need an alternative to "delay" actions on a LOOP. When using time.sleep(1) the whole process pauses for a second. The print 'something' should be executed after every 1 second, 50 times and not interrupting the rest of the process.

Actual code:

for num in range(50, -1, -1):
    print 'something'
    time.sleep(1)

Upvotes: 1

Views: 1000

Answers (1)

Amadan
Amadan

Reputation: 198324

If I understand what you want, you need to use threads. One thread will do exactly what you did: just count and sleep. The other thread will be "the rest of process", doing whatever it wants, without being interrupted by sleeping.

import time
import threading

def count():
    for num in range(50, -1, -1):
        print 'something'
        time.sleep(1)

count_thread = threading.Thread(target=count)
count_thread.start()

for num in range(10, -1, -1):
    print 'main'
    time.sleep(5)

count_thread.join()

Upvotes: 1

Related Questions