How can I completely stop pathfinding once it has started

Basically what I want to do is create an npc that will move towards sounds, this works well until it receive another sound while moving to a previous sound, in this scenario the npc will move to the old sound and the new sound at the same time causing to walk backwards and forwards

local PFS = game:GetService("PathfindingService")

local path = PFS:CreatePath({
	AgentRadius = 3,
	AgentHeight = 10,
	AgentCanJump = false,
	AgentCanClimb = false,
	WaypointSpacing = 4
})

local figure = script.Parent
local humanoid = figure:FindFirstChild("Humanoid")
local root = figure:FindFirstChild("HumanoidRootPart")

local stopMoving = false

function moveto(pos, retries)
	retries = retries or 5
	if retries <= 0 then
		figure:SetAttribute("Animation", "Idle") 
		return
	end
	
	local success, erro = pcall(function()
		path:ComputeAsync(root.Position, pos)
	end)
	
	if success and path.Status == Enum.PathStatus.Success then
		figure:SetAttribute("Animation", "Walk")
		for i, waypoint in path:GetWaypoints() do
			if stopMoving then
				humanoid:MoveTo(root.Position)
				figure:SetAttribute("Animation", "Idle")
				return
			end
			humanoid:MoveTo(waypoint.Position)
			humanoid.MoveToFinished:Wait()
		end
	else
		figure:SetAttribute("Animation", "Idle")
		task.wait(1)
		return moveto(pos, retries - 1)
	end
	
	figure:SetAttribute("Animation", "Idle")
end

game.ReplicatedStorage:FindFirstChild("Events"):FindFirstChild("SoundSignal").OnServerEvent:Connect(function(player, sound, position)
	moveto(position)
end)

I’m just not sure how to cancel the function when it’s already started

I think You meant to write here humanoid:Move(root.Position) this: humanoid:MoveTo(root.Position)

ah yes, thank you for noticing that