Timer¶
run code on a delay or at a repeating interval.
▶ Run in browserTags: 2d timer signals
A Timer is a node that emits a timeout signal after its duration. Set
one_shot=False to repeat. Here a repeating timer spawns a pulse every 0.8s, and
each pulse uses its own one-shot timer to remove itself after one second, so the
screen stays lively without any per-frame bookkeeping in the root.
What it demonstrates¶
Timer(duration=, one_shot=, autostart=)– a node that firestimeoutafter a delay.timer.timeout.connect(fn)– run something when it fires (a signal, like any other).Repeating timers (
one_shot=False) for intervals; one-shot timers for delayed actions.
Source¶
1"""Timer: run code on a delay or at a repeating interval.
2
3A `Timer` is a node that emits a `timeout` signal after its `duration`. Set
4`one_shot=False` to repeat. Here a repeating timer spawns a pulse every 0.8s, and
5each pulse uses its own one-shot timer to remove itself after one second, so the
6screen stays lively without any per-frame bookkeeping in the root.
7
8# /// simvx
9# tags = ["2d", "timer", "signals"]
10# screenshot_frame = 90
11# web = { root = "TimerDemo", width = 800, height = 600, responsive = true }
12# ///
13
14## What it demonstrates
15
16- `Timer(duration=, one_shot=, autostart=)` -- a node that fires `timeout` after a delay.
17- `timer.timeout.connect(fn)` -- run something when it fires (a signal, like any other).
18- Repeating timers (`one_shot=False`) for intervals; one-shot timers for delayed actions.
19"""
20
21import random
22
23from simvx.core import Node2D, Timer, Vec2
24from simvx.graphics import App
25
26WIDTH, HEIGHT = 800, 600
27
28
29class Pulse(Node2D):
30 """An expanding, fading ring that deletes itself after one second."""
31
32 LIFE = 1.0
33
34 def on_ready(self):
35 self.age = 0.0
36 timer = self.add_child(Timer(duration=self.LIFE, one_shot=True, autostart=True))
37 timer.timeout.connect(self.destroy) # one-shot: clean up after the delay
38
39 def on_update(self, dt: float):
40 self.age += dt
41
42 def on_draw(self, renderer):
43 f = min(1.0, self.age / self.LIFE)
44 renderer.draw_circle(self.position, 12 + f * 64, colour=(0.4, 0.8, 1.0, 1.0 - f), filled=True)
45
46
47class TimerDemo(Node2D):
48 def on_ready(self):
49 self.ticks = 0
50 spawner = self.add_child(Timer(duration=0.8, one_shot=False, autostart=True))
51 spawner.timeout.connect(self._spawn) # repeating: fires every 0.8s
52
53 def _spawn(self):
54 self.ticks += 1
55 self.add_child(Pulse(position=Vec2(random.uniform(120, WIDTH - 120), random.uniform(140, HEIGHT - 100))))
56
57 def on_draw(self, renderer):
58 renderer.draw_text("Timer: repeating spawner + one-shot lifetimes", (20, 20), scale=2, colour=(1, 1, 1))
59 renderer.draw_text(f"ticks: {self.ticks}", (20, 52), scale=1, colour=(0.7, 0.7, 0.7))
60
61
62if __name__ == "__main__":
63 App(title="Timer", width=WIDTH, height=HEIGHT).run(TimerDemo())