I’ve been tasked with writing a function that executes a passed function every interval, passed to the function by the user. Below is the code, and how to call it:
import time
from typing import Callable
last_milliseconds: int = 0
def set_timer(interval: int, function: Callable) -> bool:
global last_milliseconds
milliseconds: int = int(round(time.time() * 1000))
done: bool = (milliseconds - last_milliseconds) >= interval
if done:
function()
last_milliseconds = milliseconds
Called by:
p: Callable = lambda: print("set_timer called.")
while True:
set_timer(1000, p)
Is there a better way to go about this? I’m unsure with the use of the global variable, and the function must be called in an infinite loop structure in order to work. Any and all feedback is accepted and appreciated.