Create a timer dynamically

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rinart73
:warning: Old Version Published before Godot 3 was released.

I get used to creating a new instances of classes in the code, not in using IDE interface.
So, here is my code:

extends Sprite

var timer;

func _ready():
    timer = Timer.new()
    timer.set_one_shot(false)
    timer.set_timer_process_mode(TIMER_PROCESS_FIXED)
    timer.set_wait_time(0.6)
    timer.connect("timeout", self, "_timer_callback")
    timer.start()
    
func _timer_callback():
    if is_hidden():
        show()
    else:
        hide()

My question is: How to define a timer timeout handler?
Updated the code. It doesn’t work.

I’m not sure but I think you need to add a child in order to connect (before start())

add_child(timer)

al.glez | 2016-05-19 02:00

Thanks, it worked

rinart73 | 2016-05-19 02:19

:bust_in_silhouette: Reply From: al.glez

I’m not quite sure if i I understood your question. But with code you can connect to a function with

timer.connect(“timeout”, self, “function”)

Thanks, please take a look at the updated code. It doesn’t work.

rinart73 | 2016-05-19 01:52

:bust_in_silhouette: Reply From: Tybobobo

You need to add the timer to the scene tree.

timer = Timer.new()
timer.set_one_shot(false)
timer.set_timer_process_mode(TIMER_PROCESS_FIXED)
timer.set_wait_time(0.6)
timer.connect("timeout", self, "_timer_callback")
timer.start()
add_child(timer) # <--------

I had the same problem. :slight_smile:

This is because GDScript has automatic reference counting and cleanup of orphaned records. When timer goes out of scope, if there is no other reference to it, it will be destroyed. Adding it to the SceneTree creates a reference from an object that will still be around when the timer expires.

jeremyjh | 2016-09-23 04:03

How would you queue_free on the timer from the callback after it’s been used? Or more simply how would you address that object after the function that created it is left?

zyrixian | 2016-10-02 21:07

Do you need to destroy the timer or is it automatically destroyed?

TGMG | 2020-06-27 19:45

Thank you so much! Lost more than 1 hour to resolve so dumb problem

Divergence19 | 2020-12-17 00:51