Signal connecting mode connect deferred please tell me the difference betwen normal and deferred

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By LordViperion

I see this in the networked pong demo proj on git
And i readed the another answers but answers is very bad not clearing with me

:bust_in_silhouette: Reply From: Zylann

In Godot, you can call functions either directly, or in a deferred way with call_deferred("function_name").
When you do the latter, the function will not be executed immediately, but queued in a list which will be flushed at the next idle time. “idle time” occurs every frame, usually when the engine finished calling all _process and _input functions.
This can be useful in some cases where your code is executed as part of an initialization process (Like _ready) and some actions like adding child nodes cannot be done immediately because the engine is already at work setting them up. Using a deferred call allows to do it when the engine finished its work.
Another interesting use of call_deferred is when your code runs in a thread and needs to notify the main thread: because calling directly is often not safe (the main thread could be using the same object in parallel), using a deferred call ensures it gets executed properly.

When you emit a signal, functions will get called on each object connected to that signal. The same rules apply here: if an object is connected to the signal in deferred mode, its function will be called with call_deferred.

In the multiplayer Pong demo, the comment suggests it allows to remove the connection from within the callback that gets called by the signal itself. Indeed, if you try to disconnect a signal from the function it has called, the engine might crash, because it is currently using that signal to call the function and that would “pull out the rug under its feet”.

Or, if you put it like pseudocode:

for function in functions_list:
	# If this modifies `functions_list` while we iterate on it, we are in trouble

“if you try to disconnect a signal from the function it has called, the engine might crash, because it is currently using that signal”

Or if I try to connect to signal from the function,the engine will be crashing like try disconnect? Because connecting modify functionlist?

LordViperion | 2019-01-25 14:29

Yeah likely. I haven’t tested this case, though. If it fails, either use deferred connection, or make the new connection with a deferred call. There is also the CONNECTION_ONESHOT mode to make it auto-disconnect after the first emission.

Zylann | 2019-01-25 17:12