call a function every n mseconds

Jonas Galvez jonas at jonasgalvez.com
Sun Feb 22 17:48:49 CET 2004


> [Vedran Furac]
> How can I call a function every time a specified number of
> milliseconds elapses? Javascript has setInterval() function and I
> need something like that.

Funny, yesterday I was looking for exactly the same thing. I ended up
creating a small module with a somewhat hackish implementation of
setInterval and clearInterval, but it's been OK for my needs:


from threading import Timer

def setInterval(f, i, *params):
    def fWrapper():
        apply(f, params)
        fWrapper.t = Timer(i, fWrapper)
        fWrapper.t.start()
    fWrapper.t = Timer(i, fWrapper)
    fWrapper.t.start()
    return fWrapper

def clearInterval(timerRef):
    timerRef.t.cancel()


Hope it works out for you.


Jonas








More information about the Python-list mailing list