Is this correct or am I dumb?

Godot Version

Godot v4.4

Question

I wanted a way to await for a signal for some time but “cancel” that await after that time is up.
I came up with this method but I don’t know if it is correct

func await_signal_with_timeout(s:Signal, time:int):
	var on_timer_goes_out = func():
		print_debug("The timer goes out ")
		s.emit()
	
	var timer := get_tree().create_timer(time)
	timer.timeout.connect(on_timer_goes_out)
	
	var on_signal_fires = func():
		print_debug("The signal was received now. Cancelling timer")
		if timer.timeout.is_connected(on_timer_goes_out): 
			timer.timeout.disconnect(on_timer_goes_out)
		
	
	s.connect(on_signal_fires)
	await s
	s.disconnect(on_signal_fires)

So then it is used like this

await await_signal_with_timeout(camera_bounds.camera_set,5)

It is working in my game and as far as I know it is ok, but I’m afraid I’m missing something or doing something that goes agains the programming patterns godot enforces.

I guess this can be troublesome for signals that carry parameters but I also gues I could work around that

I guess if it works, it works :person_shrugging:. But it sounds hard to debug if an error happens.

1 Like