+6 votes

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.

in Engine by (46 points)
edited by

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

add_child(timer)

Thanks, it worked

2 Answers

+1 vote
Best answer

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")

by (104 points)
selected by

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

+7 votes

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. :)

by (486 points)

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.

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?

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

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.