How to stop MoveToFinished:Wait() halfway through?

So I have a script that makes an npc walk around an area randomly until a player starts a round, but whenever the player starts a round the npc will finish walking to where it’s set to walk before it stops walking and teleports. I was wondering if there’s a way to stop MoveToFinished:Wait() halfway through?

The script:

local NPC = script.Parent
local Spawner = script.Parent.Parent.Parent.Spawner
local walkToPoints = {
	script.Parent.Parent.Parent.WalkToPoints["Point 1"],
	script.Parent.Parent.Parent.WalkToPoints["Point 2"],
	script.Parent.Parent.Parent.WalkToPoints["Point 3"]
}

NPC.Humanoid.WalkSpeed = 1

local enabledValue = script.WalkEnabled
local hasTeleported = false

local animationId = "rbxassetid://15700252729"
local animation = Instance.new("Animation")
animation.AnimationId = animationId
local animationTrack

local function playAnimation()
	if not animationTrack or not animationTrack.IsPlaying then
		animationTrack = NPC.Humanoid:LoadAnimation(animation)
		animationTrack:Play()
	end
end

local function stopAnimation()
	if animationTrack and animationTrack.IsPlaying then
		animationTrack:Stop()
	end
end

local function moveTo(point)
	playAnimation()
	NPC.Humanoid:MoveTo(point.Position)
	NPC.Humanoid.MoveToFinished:Wait()
	stopAnimation()
end

while true do
	if enabledValue.Enabled == true then
		local randomIndex = math.random(1, #walkToPoints)
		local selectedPoint = walkToPoints[randomIndex]

		moveTo(selectedPoint)
		wait(2)

		hasTeleported = false
	elseif enabledValue.Enabled == false and not hasTeleported then
		NPC:SetPrimaryPartCFrame(CFrame.new(Spawner.Position))
		hasTeleported = true
	end
	wait(0.1)
end
1 Like