Measuring how long you are pressing a button

Hello. I am currently having a problem scripts. I just can’t get this to work. I tried using variables, while loops, and just anything on my mind.

Code:

mouse.Button1Down:Connect(function()
   	if active == true then
   		if cooldown == false then
   			cooldown = true
   			local seconds = 0
   			while mouse.Button1Down do
   				wait(1)
   				seconds = seconds + 1
   				if mouse.Button1Up then
   					print(tostring(seconds)) -- trying to print seconds here...
   					break
   				end
   			end
   			
   			wait(waitTime)
   			player.Character.Humanoid.WalkSpeed = 10
   			cooldown = false
   			seconds = 0
   		end
   	end
end)

Thanks for reading!

You may be able to use os.time or os.clock or time to measure elapsed time instead of using wait and a seconds count incrementation. Are you using a Gui button or an in-game part button?

I recommend recording the start time as a local variable on Button1Down and recording a finish time on Button1Up. Then just subtract the two for elapsed time.

1 Like

I am using a tool 30 charrrddrfss

Here’s an idea I had:

local ButtonDown = false
local SecondsDown = 0

mouse.Button1Down:Connect(function()
ButtonDown = true
end)

mouse.Button1Up:Connect(function()
ButtonDown = false
print(SecondsDown) 
SecondsDown = 0
end)

While ButtonDown == true do
SecondsDown = SecondsDown + 0.001
wait(0.001)
end

This goes by milliseconds btw, not seconds.

Edit: Now it’s milliseconds

Not to be picky, but milliseconds is measured in .001 seconds, not .01 seconds.

1 Like

You can await mouse.Button1Up being fired inside your Mouse1Down event.

mouse.Button1Down:Connect()
    local start = tick()
    mouse.Button1Up:Wait() --// pause thread until Button1Up is fired

    local heldFor = tick() - start --// the current time - the start time = time passed

    print(heldFor)
end
5 Likes

GGGGG14 and EpicMetatableMoment, you both have correct solutions… thank you for your help!

3 Likes

Since you’re using a Tool, it’d be the best to use the .Activated event. Here’s the example I made for you:

local Tool = script.Parent -- The Tool.
local TimeStart = nil

Tool.Activated:Connect(function()
	TimeStart = os.time() -- This will tell us in UNIX time when you activated the tool.
end)

Tool.Deactivated:Connect(function()
	print("You activated the tool for " ..os.difftime(os.time(), TimeStart).. " seconds!") -- os.difftime returns the number of seconds from t1 to t2
	TimeStart = nil
end)
1 Like