3

I'm trying to create a JavaScript-like setInterval function in python, but I'm stumped now on how to make a similar clearInterval.

 def setInterval(func, sec):
     def inner_function():
         func() # call on it
         setInterval(func, sec) # do the same function over and over again
     thread = threading.Timer(sec, inner_function) # have it call inner ever x seconds
     thread.setDaemon(True) 
     thread.start()
     return thread

def clearInterval(interval):
    interval.cancel()
    return True

So at first I thought this should work

interval = setInterval(lambda: print("Hello, World!"), 3) # prints 'Hello, World!' every three seconds.
# some time later
clearInterval(interval)

Trying to clear the interval did not work though. It makes a clone thread that keeps executing the func

Is there a way to restart a thread in python? If there is not a way does anyone know how to do the above, only have it actually be able to use clearInterval and it will stop entirely?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
user3234209
  • 935
  • 2
  • 8
  • 14
  • related: [Python Equivalent of setInterval()?](http://stackoverflow.com/q/2697039/4279) – jfs Mar 18 '14 at 06:31
  • 1
    here's [`setInterval()`'s implementation with `clearInterval()` (`stop.set()`)](http://stackoverflow.com/a/16368571/4279) – jfs Mar 18 '14 at 06:33

0 Answers0