Python 相当于 JavaScript 的 setTimeout 和 setInterval [关闭]

问题描述 投票:0回答:0

这不是问题,只是提出了我为 setTimeout 和 setInterval 想出的解决方案,但是是在 Python 中。

通过本课程,您可以:

  1. 使用间隔 ID 设置超时(通过变量,不是必需的)。
  2. 以与超时相同的方式设置间隔。
  3. 设置一个带有ID的间隔,然后设置一个超时,在给定的时间内取消间隔。
  4. 用一个ID设置超时,用另一个setTimeout取消超时。

我知道它看起来很复杂,但我需要它的所有功能,就像在 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)

希望这有帮助。

python settimeout setinterval
© www.soinside.com 2019 - 2024. All rights reserved.