Help with timer.delay()

Hi, I’m trying to make it so that a value will decrease 1 unit per second while a while a certain set of parameters are correct using the time.delay().

I assumed that you just put the number of seconds you want to delay by in the brackets but apparently not? I did look on the documentation but there isn’t any clear examples there. I was just wondering how to do this and if the way I’m going about this is even right in the first place? (which it’s probably not)

function update(self, dt)
	if fuel < 0 then
		thrust = 0
	elseif fuel > 0 then
		timer.delay(1)
		fuel = fuel - 1
	end
end

So basically I want it so fuel decreases by 1 per second while it’s greater than 0.

Thanks for any help.

It won’t work. Better to do everything in init:

function init(self)
    self.fuel = INITIAL_FUEL
    self.thrust = 1
    self.fuel_timer = timer.delay(1, true, function()
		self.fuel = self.fuel - 1
        if self.fuel < 0 then
            self.thrust = 0
            timer.cancel(self.fuel_timer)
        end
	end)
end

3 Likes

Thank you very much this helped a lot!

Note that timer.delay(1) will not stop execution for one second and then decrease fuel by 1. The timer.delay() function is asynchronous and will call the provided function (like enotofil showed).

2 Likes