Best practice for referencing passed time?

Hi,

For the purpose of a function I need to reference the time between calls of the function. The specific function isnt really important, but it leads me to the problem of whats the best way to find this time interval.

I have an ideas of how to do this but Im not sure if this is the best way to go about it

My idea is create a total time variable and update it by connecting to RunService.Stepped

local RunService = game:GetService("RunService")

local time = 0
RunService.Stepped:Connect(function(t,dt)
    time = t
end)

local oldTime = 0
function doStuff()
    local timeElapsed = time - oldTime
    oldTime = time
    --do stuff with timeElapsed
end

Normally i would be fine with this but ive been reading examples on the dev forum of bad coding practices and it turns out i do alot of them. So since im going to be using this functionality in many different places i would appreciate if somebody could tell me if this is fine to do, or whats a better way. Thanks

1 Like

Can’t you just use os.clock?

local oldTime = os.clock()

function doStuff()
	local timeElapsed = os.clock() - oldTime
	oldTime = os.clock()
	--do stuff with timeElapsed
end
1 Like

Oh wow thats perfect :open_mouth: Thank you I didnt know about that

1 Like