Timers in GDScript

Our first example demonstrates how to use timers in GDScript. Timers are useful when you want to execute code at some point in the future or repeatedly at some interval.

extends Node

func _ready():
    # Timers represent a single event in the future. You
    # tell the timer how long you want to wait, and it
    # will emit a signal when that time has elapsed.
    # This timer will wait 2 seconds.
    var timer1 = Timer.new()
    timer1.set_wait_time(2.0)
    timer1.set_one_shot(true)
    timer1.connect("timeout", self, "_on_Timer1_timeout")
    add_child(timer1)
    timer1.start()

    # If you just wanted to wait, you could have used
    # yield(get_tree().create_timer(2.0), "timeout").
    # One reason a timer may be useful is that you can
    # stop the timer before it fires. Here's an example of that.
    var timer2 = Timer.new()
    timer2.set_wait_time(1.0)
    timer2.set_one_shot(true)
    timer2.connect("timeout", self, "_on_Timer2_timeout")
    add_child(timer2)
    timer2.start()

    # Stop timer2 before it has a chance to fire
    timer2.stop()
    print("Timer 2 stopped")

    # Give timer2 enough time to fire, if it ever
    # was going to, to show it is in fact stopped.
    yield(get_tree().create_timer(2.0), "timeout")

func _on_Timer1_timeout():
    print("Timer 1 fired")

func _on_Timer2_timeout():
    print("Timer 2 fired")

To run this script, attach it to a Node in your Godot scene. When you run the scene:

Timer 1 fired
Timer 2 stopped

The first timer will fire approximately 2 seconds after we start the program, but the second should be stopped before it has a chance to fire.

In GDScript, we use the built-in Timer node to create timers. We can set the wait time, whether the timer should repeat or fire only once (one-shot), and connect to its “timeout” signal to execute code when the timer fires.

Unlike in some other languages, GDScript doesn’t have built-in channels for communication between timers and the main thread. Instead, we use signals and callbacks to handle timer events.

The yield function in GDScript can be used for simple delays, similar to time.Sleep in some other languages. However, using Timer nodes gives us more control and allows us to stop the timer if needed.

Remember that in Godot, all nodes (including Timers) need to be added to the scene tree with add_child() to function properly.