Skip to reading
GDScript Programming & Godot

17. Waits, timers and elapsed time

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView illustrations
Code example
func run() -> String:
    await get_tree().create_timer(0.01).timeout
    return "Finished waiting"

await suspends this function until the signal or coroutine completes. It yields control to the engine; it does not freeze the whole game. A caller that needs the result must await this function too.

Code example
var ticker: Timer
var ticks: int = 0
Code example
func on_global_ready(event: Dictionary = {}) -> void:
    ticker = Timer.new()
    ticker.wait_time = 1.0
    add_child(ticker)
    ticker.timeout.connect(_on_tick)
    ticker.start()
Code example
func _on_tick() -> void:
    ticks += 1
    Log("Timer ticks: " + str(ticks))

Turn on Keep global instance alive for this repeating-timer record. on_global_ready is called after PCA binds the runtime. The Timer is owned by the script, so it is freed with that instance. stop pauses future timeout emissions; start begins it again.

For measuring durations, Time.get_ticks_msec/usec is monotonic. Time.get_unix_time_from_system is the calendar clock and can change. A default SceneTree timer processes while the tree is paused; pass process_always=false if it should pause with the tree.

Figure 6. A persistent timer script keeps its counter between ticks.

Page 26 of 378Permalink
Go to page