Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

"wait()" not correctly waiting the time?

Basically i wanted a timer correct to 3 Decimal places, to do this i had to use "BodyGyro" as "IntValue" doesn't allow decimals, The problem I'm having is that it doesn't seem to count up correctly meaning its time is completely off, I might be missing something obvious as it is late but i just cant figure it out, here is the script:

local Timer = game.Players.LocalPlayer.PlayerGui.Player_Cache.Timer
local GTime = game.Players.LocalPlayer.PlayerGui.Player_Cache.Timer.Time

while true do wait(0.001)
	if Timer.Value == true then
		GTime.D = GTime.D + 0.001
		script.Parent.Text = string.format("%.3f", GTime.D)
	end 
end

Once again sorry if its obvious.

2 comments

1

Goodness gracious, don't use BodyGyro, just create a variable! Also, computers do a lot of things at once. You can never expect your code to yield an exact amount of time before resuming again -- it has other things to do! wait is always an approximation, and it has a lower limit at nearly 0.03 seconds (depending on the environment). You achieve minimal time with wait by passing no arguments.

0

Yea i didn't know NumberValue was a thing and IntValue didn't allow decimals so i took whatever i got haha, thank you for your help!

1 answer

✓ Accepted answer

You should at least use a NumberValue to store a number, rather than a BodyGyro! (As ScriptGuider suggested, it's possible you just need a variable, but if you want to be able to set a starting value in an instance instead of code, or if other code needs to read the current time, an instance like a NumberValue is the simplest way to do that).

Also, writing == true is redundant; you can just say if Timer.Value then.

wait has a minimum time that it will wait. Usually that's around one thirtieth of a second, but it can be much more if the game is busy, lagging behind, or the game has lost focus, among any other number of things.

Luckily, wait() returns the actual amount of time that was waited. So here's what you need to change:

local elapsed = wait()
if Timer.Value then
	Time.Value = Time.Value + elapsed
	script.Parent.Text = string.format("%.3f", Time.Value)
end

Since you won't get wait to actually wait for a single millisecond, you might as well just pass it no parameters (equivalent to passing it the number 0). This just waits the smallest amount of time possible.

If you want something slightly speedier, you can use game.RunService.Heartbeat:Wait() instead of wait(). This will guarantee your time is scheduled every single frame.

1 comment

0

Thank you I'm still relatively new to scripting so everything helps and its working perfectly now so much appreciated!

This discussion is preserved as it was. New answers, comments, and votes are closed.