这不是问题,只是提出了我为 setTimeout 和 setInterval 想出的解决方案,但是是在 Python 中。
通过本课程,您可以:
我知道它看起来很复杂,但我需要它的所有功能,就像在 JavaScript 中一样。请注意,您需要预先创建一个函数并将函数名称用作参数(参见代码)。
#If I'm not mistaken, I believe the only modules you need are time and threading. The rest were for something I'm working on.
import time
import math
import pygame
import threading
import ctypes
from sys import exit
#Functions
class Timer:
def __init__(self):
self.timers = {}
self.timer_id = 0
def setInterval(self, fn, time, *args):
def interval_callback():
fn(*args)
if timer_id in self.timers:
self.timers[timer_id] = threading.Timer(time/1000, interval_callback)
self.timers[timer_id].start()
timer_id = self.timer_id
self.timer_id += 1
self.timers[timer_id] = threading.Timer(time/1000, interval_callback)
self.timers[timer_id].start()
return timer_id
def clearInterval(self, timer_id):
if timer_id in self.timers:
self.timers[timer_id].cancel()
del self.timers[timer_id]
def setTimeout(self, fn, delay, *args, **kwargs):
def timer_callback():
self.timers.pop(timer_id, None)
fn(*args, **kwargs)
timer_id = self.timer_id
self.timer_id += 1
t = threading.Timer(delay / 1000, timer_callback)
self.timers[timer_id] = t
t.start()
return timer_id
def clearTimeout(self, timer_id):
t = self.timers.pop(timer_id, None)
if t is not None:
t.cancel()
t = Timer()
#Usage Example
lall = t.setInterval(print, 1000, "hi")
t.setTimeout(t.clearInterval, 3000, lall)
希望这有帮助。