Help with elseif timer

Hello, devs! :happy3:

I made a dynamic timer that counts up, and after certain points in time, the timer’s text is updated.

As well as being a nightmare to debug, this code runs horribly and inefficiently due to all the elseif statements. I was wondering if there was a more efficient way to do this, one that isn’t an eyesore.

Prepare yourselves mentally:

local function renderSplash()
	if ransplash == splashes[10] then
		while wait() do
			if math.round(time()) < 59 then
				splash.Text = "You've been here for "..math.round(time()).." seconds!"
			elseif math.round(time()) <= 119 then
				splash.Text = "You've been here for ".. math.round(time()) / 60 .." minute!"
			elseif math.round(time()) >= 120 then
				splash.Text = "You've been here for ".. math.round(time()) / 60 .." minutes!"
			elseif math.round(time()) >= 3599 then
				splash.Text = "You've been here for a really long time!"
			end
		end
	else
		splash.Text = ransplash
	end
end

:sad:
Is there a way to do this more efficiently? How should I make this better?

you could look into using math to figure out hours, minutes, seconds with modulos and use string formating to condense it without having multiple if statements like you have there

How would I use string formatting in this situation anyways? And math too?

you can use the os library for this

os.date() returns a dictionary with the time broken down into units and you can loop through them to generate a message

local startTime = os.time()

while task.wait(1) do
	
	local timeInfo = os.date("*t", os.time() - startTime)
	print(timeInfo)

end

--example of what os.date() returns
--[[

{
    ["day"] = 31,
    ["hour"] = 19,
    ["isdst"] = false,
    ["min"] = 8,
    ["month"] = 12,
    ["sec"] = 20,
    ["wday"] = 4,
    ["yday"] = 365,
    ["year"] = 1969
} 

Ah, I can use this as a base. Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.