How to cancel a function if it is not finished?

Well, the following script is supposed to work when you have the mouse pressed, but after I stop pressing it it still works the same and does not stop, I need it to stop working when the mouse is not held down and to work again when it is pressed

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local mouse = localPlayer:GetMouse()
local Button = script.Parent

Button.MouseButton1Down:Connect(function()
mouse.Move:Connect(function(Y)
Button:TweenPosition(UDim2.new(0.5, 0, mouse.Y/mouse.ViewSizeY, 0), nil, nil, 0.01)
end)
end)
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local mouse = localPlayer:GetMouse()
local Button = script.Parent

local shouldMouseMove = true

Button.MouseButton1Down:Connect(function()
   shouldMouseMove = true
   mouse.Move:Connect(function(Y)
      if not shouldMouseMove then return end
      Button:TweenPosition(UDim2.new(0.5, 0, mouse.Y/mouse.ViewSizeY, 0), nil, nil, 0.01)
   end)
end)

Button.MouseButton1Up:Connect(function()
   shouldMouseMove = false
end)

Try this. I haven’t tested it out for myself, so if there are any errors, you can tell me.

Better to just disconnect the event connection:

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local mouse = localPlayer:GetMouse()
local Button = script.Parent

local moveEvent = nil

Button.MouseButton1Down:Connect(function()
	moveEvent = mouse.Move:Connect(function(Y)
		Button:TweenPosition(UDim2.new(0.5, 0, mouse.Y/mouse.ViewSizeY, 0), nil, nil, 0.01)
	end)
end)

Button.MouseButton1Up:Connect(function()
	if moveEvent then
		moveEvent:Disconnect()
		moveEvent = nil
	end
end)
1 Like

Oh yeah, I didn’t think of that :man_facepalming: Thats the best solution.

1 Like

Well it should work but it doesn’t work, the other guy’s script worked if you clicked again, this one doesn’t

Not quite sure what you mean. Is there an error? There might be something else wrong with the code that was supplied.

I don’t think you want to use TweenPosition for this. Just set the position directly (in addition to @jmt99’s answer):

Button.Position = UDim2.new(0.5, 0, mouse.Y/mouse.ViewSizeY, 0)