How to put a time gap between the lines of codes?

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

I’m trying to do an experiment where a line of code is executed and then few seconds (e.g. 3 seconds) later, the next line of code will run. This is the code I used for this experiment.

extends Node

func _ready():
	print("Process ready!\n")

func _process(delta):
	var wait_time

	print("Process ongoing...\n")

	wait_time = 10000000
	while wait_time > 0:
		wait_time -= 1



However, the code didn’t work like I expected. The scene window just stayed there for a while and the 3 lines of text appeared on the output window almost simultaneously before the scene window closed a spilt second later. Is there anything wrong with the code? And is there a better way to achieve this?

:bust_in_silhouette: Reply From: AndyCampbell


Welcome to the Godot forums.

I would expect that to all happen quickly - ready() is called as soon as the object is ready to process, then _process(delta) is called every frame so the next line will appear 1 frame later. The the third line will print after you count to 10 milliion (which does not take long - on my computer that is 490ms)

The approach you are taking will be very inefficient - you are asking your CPU to count to 10 million as quickly as it can. That will max out your CPU until it is complete. The length of the delay will vary depending on how fast your computer is, so that will not give you a predictable delay. Also, when you run that inside _process you are asking Godot to do that every frame - maybe 30 or 60 times a second. Forcing the CPU to 100% is not good practice :slight_smile:

Much better to use a Timer. Documentation is here. The principle of the Timer is that you setup the timer, then it runs for a configurable time (using minimal CPU) and then calls a configurable function when it is done. Check out the docs for details.

You can add timers in the scene tree. There is a nice tutorial here or you can find many more online

Or, a shortcut to add an inline timer is:

yield(get_tree().create_timer(3), "timeout")

This line pauses your code for 3 seconds and lets Godot do something else. When the timer is done, it comes back to where it was.