Does Python have a function similar to JavaScript's setInterval()
?
I would like to have:
def set_interval(func, interval): ...
That will call func
every interval
time units.
Nested setTimeout calls are a more flexible alternative to setInterval , allowing us to set the time between executions more precisely. Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(func) ) is used to schedule the call “as soon as possible, but after the current script is complete”.
The setInterval() method is JavaScript is used to evaluate an expression at intervals. Here's the syntax: setInterval(function, interval_in_milliseconds, param1, param2, param3...) Here, interval_in_milliseconds sets the intervals in milliseconds, after the code will execute.
Introduction to JavaScript setInterval() The setInterval() repeatedly calls a function with a fixed delay between each call. In this syntax: The callback is a callback function to be executed every delay milliseconds.
This might be the correct snippet you were looking for:
import threading def set_interval(func, sec): def func_wrapper(): set_interval(func, sec) func() t = threading.Timer(sec, func_wrapper) t.start() return t
This is a version where you could start and stop. It is not blocking. There is also no glitch as execution time error is not added (important for long time execution with very short interval as audio for example)
import time, threading StartTime=time.time() def action() : print('action ! -> time : {:.1f}s'.format(time.time()-StartTime)) class setInterval : def __init__(self,interval,action) : self.interval=interval self.action=action self.stopEvent=threading.Event() thread=threading.Thread(target=self.__setInterval) thread.start() def __setInterval(self) : nextTime=time.time()+self.interval while not self.stopEvent.wait(nextTime-time.time()) : nextTime+=self.interval self.action() def cancel(self) : self.stopEvent.set() # start action every 0.6s inter=setInterval(0.6,action) print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime)) # will stop interval in 5s t=threading.Timer(5,inter.cancel) t.start()
Output is :
just after setInterval -> time : 0.0s action ! -> time : 0.6s action ! -> time : 1.2s action ! -> time : 1.8s action ! -> time : 2.4s action ! -> time : 3.0s action ! -> time : 3.6s action ! -> time : 4.2s action ! -> time : 4.8s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With