Timeouts in GDScript

Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in GDScript is possible using coroutines and signals.

extends Node

func _ready():
    # For our example, suppose we're executing an external
    # call that returns its result after 2 seconds.
    # We'll use a coroutine to simulate this delay.
    var result1 = yield(execute_with_delay("result 1", 2.0), "completed")
    
    # Here's the timeout implementation.
    # We'll use a Timer to implement the timeout.
    var timer = Timer.new()
    add_child(timer)
    timer.set_one_shot(true)
    timer.set_wait_time(1.0)
    timer.start()
    
    # We'll use yield to wait for either the result or the timeout
    var which = yield(self, "timeout_or_result")
    
    if which == "result":
        print(result1)
    else:
        print("timeout 1")
    
    # If we allow a longer timeout of 3s, then we'll get the result
    timer.set_wait_time(3.0)
    timer.start()
    
    var result2 = yield(execute_with_delay("result 2", 2.0), "completed")
    which = yield(self, "timeout_or_result")
    
    if which == "result":
        print(result2)
    else:
        print("timeout 2")

func execute_with_delay(result, delay):
    yield(get_tree().create_timer(delay), "timeout")
    emit_signal("timeout_or_result", "result")
    return result

func _on_Timer_timeout():
    emit_signal("timeout_or_result", "timeout")

signal timeout_or_result(which)

In this GDScript version:

  1. We use coroutines (with yield) to simulate the delayed execution of external calls.

  2. Instead of channels, we use Godot’s built-in signal system to communicate between different parts of the code.

  3. We use a Timer node to implement the timeout functionality.

  4. The execute_with_delay function simulates an operation that takes some time to complete.

  5. We use the timeout_or_result signal to determine whether we got a result or a timeout.

Running this program would show the first operation timing out and the second succeeding:

timeout 1
result 2

Note that in GDScript, we don’t have direct equivalents to Go’s goroutines or channels. Instead, we use coroutines and signals, which are more idiomatic in the Godot engine environment. The overall logic and flow of the program remain similar to the original Go example.