Timer.delay doesn't fire (solved)

Hi - I am making a shoot 'em up and I want to call a function 2 seconds after my player is destroyed.

I found the timer.delay method, and think I’ve added it correctly but it doesn’t seem to run the callback.

I am using the following code:

function on_message(self, message_id, message, sender)

	-- Collide with enemy
	if message_id == hash("collision_response") and message.other_group == hash("enemies") then

			local pos = go.get_position()
			factory.create( 'fx#explode', pos, nil, { type = hash( "large" ) } )

			timer.delay( 2, false, 
				function( self, handle, time_elapsed )
					msg.post( '/game', 'player-dead' )
				end 
			)

			go.delete()
	end

If I run the msg.post without the timer.delay then it works as I expect. With the timer.delay the code runs with no errors but nothing happens when the player is removed.

Have I missed something/ done something wrong?

Thanks!

The problem is that you delete the game object using go.delete() and since the game object is deleted so is the script component that started the timer. When this happens the timer will be cancelled as well.

You should move the go.delete() to inside the timer.delay() callback. If you need to hide things like sprites you can disable them using msg.post("#mysprite", disable")

1 Like

ah ha - that makes sense. I shall try that instead then. Thanks!

Update: That worked. Thanks again :slight_smile:

1 Like