How to check whether a player has held a text button for x amount of time?

Hello there! I was wondering if it was possible to check whether a player has held a text button for x amount of time (in my case 5 seconds). All support will appreciated. Here is my script.

local count = 0

while script.Parent.MouseButton1Down do
	if count >= 5 then
		print("Done")
		break
	else
		count += 1
	end
	wait(1)
end

script.Parent.MouseButton1Up:Connect(function()
	count = 0
end)
1 Like

Here is some code I tested that might meet your needs:

local button = script.Parent.TextButton

-- track mouse click and release times with some variables global to the functions below
local mouseButton1DownTime
local mouseButton1UpTime
local mouseButton1Seconds

local function leftMouseButton1Down(x, y)
	mouseButton1DownTime = time()
end


local function leftMouseButton1Up(x, y)
	mouseButton1UpTime = time()
	mouseButton1Seconds = mouseButton1UpTime - mouseButton1DownTime
	if mouseButton1Seconds >= 5 then
		print("mouse down for 5 or more seconds.")
		print("mouse down for ", mouseButton1Seconds , " seconds.")
	else
		print("shorter click")
		print("mouse down for ", mouseButton1Seconds , " seconds.")
	end
end

button.MouseButton1Up:Connect(leftMouseButton1Up)
button.MouseButton1Down:Connect(leftMouseButton1Down)

Here is how I have the GUI setup. The script RunContext is set to Client
image

Here is the output:
10:38:58.363 shorter click - Client - Script:20
10:38:58.363 mouse down for 0.06666667014360428 seconds. - Client - Script:21
10:39:07.546 mouse down for 5 or more seconds. - Client - Script:17
10:39:07.546 mouse down for 6.683333681896329 seconds. - Client - Script:18

Here is another option if you need the code to do something as soon as the button is held for 5 seconds:

local button = script.Parent.TextButton

-- track mouse click and release times with some variables global to the functions below
local mouseButton1DownTime
local mouseButton1Seconds
local mouseLoopActive = false

local function mouseLoop()
	while mouseLoopActive do
		mouseButton1Seconds = time() - mouseButton1DownTime
		if mouseButton1Seconds >= 5 then 
			print("Done. Mouse down for 5 seconds.")
			mouseLoopActive = false
		end
		wait(0.2)
	end
end

local function leftMouseButton1Down(x, y)
	mouseButton1DownTime = time()
	mouseLoopActive = true
	mouseLoop()
end


local function leftMouseButton1Up(x, y)
	mouseLoopActive = false
end

button.MouseButton1Up:Connect(leftMouseButton1Up)
button.MouseButton1Down:Connect(leftMouseButton1Down)