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)
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:
IfClickPressed
is set to true
by your code.wait(3)
. Since IfClickPressed
is true, it enters the while loop.ItsBeingPressedLol
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.