How to stop executing a function for a certain amount of time, without going back to the first function?

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

In this code:

func _first_function():
    second(function)
    ...other code...

func _second_function():
    yield(get_tree().create_timer(1), "timeout"

The second function will stop executing for 1 second, but before the time is out it will go back to the first function, is there anyway to stop executing the called function without going back to the calling one ?

:bust_in_silhouette: Reply From: avencherus

Yes, in the latest versions at least, there is a completed signal you can use for functions, so just yield the first function as well, until it is finished. The results can also be stored in a variable and checked following the yield if needed.

func function1():
	print("a")
	yield(function2(), "completed")
	print("c")
	
func function2():
	yield(get_tree().create_timer(1.0), "timeout")
	print("b")

Your code works, thank you!

soulldev | 2019-04-30 12:31

:bust_in_silhouette: Reply From: Xrayez

When yield is called in second function it implicitly returns GDScriptFunctionState object which can emit completed signal once it’s done executing, so the first function can be rewritten like this:

func _first_function():
    var state = _second_function()
    yield(state, "completed")

Or simply:

func _first_function():
    yield(_second_function(), "completed")

The first approach is more useful If you’re not sure whether the second function is going to return GDScriptFunctionState or it’s supposed to return some other object or value, so you can do this instead:

func _first_function():
    var result
    var ret = _second_function()

    if ret is GDScriptFunctionState:
        # yielding to signal to get the return value from second function
        var state = ret
        ret = yield(state, "completed")
    else:
        result = ret

    return result 

So the second approach is used when the second function returns a value, Thank you!, i got it.

soulldev | 2019-04-30 12:36