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

why does my while true do loop print double and triple and more each time I click?

Im just testing a loop that if I press 3 seconds it starts printing

but each time I click it gets faster possibly getting tripled does anyone know why everytime I click it gets faster?, by that I mean the printing

local Mouse = game.Players.LocalPlayer:GetMouse()
local IfClickPressed = false

Mouse.Button1Down:Connect(function()
IfClickPressed = true 
wait(3)
if IfClickPressed == true then
	
	
	while IfClickPressed ==  true do
		wait()
		print('ItsBeingPressedLol')
		if IfClickPressed ~= true then 
			break
			
		end
		
		
	end
end
	
	


end)


Mouse.Button1Up:Connect(function()
	
	IfClickPressed = false
	
	
	
end)

2 comments

0

try changing break to return? also u dont need the line 7 if statement

0

it kinda works but it still happens

1 answer

It happens because every time you click the mouse, a new coroutine is created (to run the function on lines 4 through 25). Let's imagine this sequence of events happens:

  • You click (at "time 0"). A coroutine/thread is created to run the function on line 4. IfClickPressed is set to true by your code.
  • You stop clicking (at time 0.5). Button1Up runs and IfClickPressed is now false.
  • You click again (say at time 2.5). IfClickPressed is true again.
  • At time 3.0, the first thread resumes from its wait(3). Since IfClickPressed is true, it enters the while loop.
  • At time 3.03 or so, that first thread now prints out your ItsBeingPressedLol message.
  • If you keep holding down the mouse button, by time 5.53, you will have 2 threads printing out your debug message!

You can fix this by using debounce, ensuring that only one function will run at a time, or by allowing only the most recent coroutine to continue by using a variable like so:

local callNum = 0
Mouse.Button1Down:Connect(function()
	callNum = callNum + 1
	local num = callNum
	wait(3)
	while num == callNum do
		print('ItsBeingPressedLol')
		wait() -- note: always check whether num == callNum after every wait
	end
end)
Mouse.Button1Up:Connect(function()
	callNum = callNum + 1
end)

No matter what the user does, only one thread will ever print something at a time. A handy line if you have more wait() commands is if num ~= callNum then return end. Whether you want this system or the debounce system I linked is of course up to you.

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