How to get exact time between inputs

Hi! I am trying to make a block of code that calculates the amount of time a player’s left mouse button is being held down. The variable is called timeDrag, and resets whenever a player is pressing the left mouse button (this sets dragging to true). Since I want milliseconds and so on, I cannot update it every second. The current code I am using doesn’t work at all, there is a huge margin of error between the real life time and the timeDrag time.

   repeat
    	timeDrag = timeDrag + 0.001
    	wait(0.001)
    until dragging == false
1 Like

I believe that the minimum wait() is around 0.036 seconds, so your wait in this loop would round up to 0.036 giving you an inaccurate measurement.

On the constructive side of things, you could try using RenderStepped as that fires every frame (60/sec) for a more accurate measure of time.

Ideally, you’d want to specify a higher amount in your wait() (e.g. higher than 0.036) so you can get very accurate results.

Good luck

2 Likes

If you’re looking for exact times, I think using tick() will help you a lot, as well as making use of the events Mouse.Button1Down and Mouse.Button1Up.

Tick() gets you a very accurate time measurement., and you’ll need 2 of them to get what you’re looking for. Typically it’d be like this:

--Let's assume Mouse is already set.
local TickSave = 0

Mouse.Button1Down:Connect(function()
TickSave = tick()
end)

Mouse.Button1Up:Connect(funciton()
local Time = tick()-TickSave
    if Time>=10 then    --Or what ever time you're looking for.
    --Your code here.
    end
end)
5 Likes

This is a very good measure of time but I believe the OP wants it down to the millisecond of precision and I believe tick() only is down to the exact second.

1 Like

It does do milliseconds as shown here:

Opening the command bar in studio and putting in print(tick()) will give that output.
Though given the method that tick() uses to get the time, this is why you need 2 of them and subtract from the most recent tick().

1 Like

Aaah I see! I tried changing my wait up to 0.05 seconds, it works perfectly!
I’ve never used tick() in my scripts before but I guess I could give it a try :slight_smile:

1 Like

Works like a charm :smiley: Thanks to both of you! :smiley:

2 Likes