Help improve simple enemy ai script

I am making an enemy and i made a simple script to follow the player if it is in a area, then when the player leaves it will stop but there are a lot of problems with the script

local rig = script.Parent
local electricarea = script.Parent.Parent["Electric Area"]
local area = {}
area.CFrame = CFrame.new(-3328.699, 131.421, -4901.823) -- center of arena
area.Size = Vector3.new(1239.84, 226.444, 608.11) -- size of arena
area.OverlapParams = OverlapParams.new()
area.OverlapParams.FilterType = Enum.RaycastFilterType.Whitelist

local walkanim = rig.Humanoid.Run
local loadwalk = rig.Humanoid:LoadAnimation(walkanim)

local swinganim = rig.Humanoid.SwingSword
local loadswing = rig.Humanoid:LoadAnimation(swinganim)
function getCharactersInArena()
	local whitelist = {}
	for _,player in pairs(game.Players:GetChildren()) do
		if player.Character ~= nil and player.Character:FindFirstChild("HumanoidRootPart") ~= nil then
			table.insert(whitelist,player.Character.HumanoidRootPart)
		end
	end
	area.OverlapParams.FilterDescendantsInstances = whitelist
	local arr = workspace:GetPartBoundsInBox(area.CFrame,area.Size,area.OverlapParams)
	return arr
end

local function findNearestPlayer(boss)
	local characters = {}
	local charactersInArena = getCharactersInArena()

	for _,root in pairs(charactersInArena) do
		local player = game.Players:GetPlayerFromCharacter(root.Parent)
		local arr  = {}
		arr.Player = player
		arr.Character = player.Character
		arr.Position = player.Character.HumanoidRootPart.Position
		arr.Magnitude = (boss.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude
		table.insert(characters,arr)
	end

	table.sort(characters,function(a,b) return a.Magnitude < b.Magnitude end)
	return characters[1]
end
local canwalk = true
rig.Humanoid.MoveToFinished:Connect(function()
	canwalk = false
	loadwalk:Stop()
	loadswing:Play()
	script.Parent["electric twin vfx"].HitBoxDamage.Kill.Disabled = false
	wait(1)
	script.Parent["electric twin vfx"].HitBoxDamage.Kill.Disabled = true
	canwalk = true
end)

while wait(1) do
	if canwalk == true then
	local root = rig.HumanoidRootPart
	local nearestPlayer = findNearestPlayer(rig)
	if nearestPlayer ~= nil then
		rig.Humanoid:MoveTo(nearestPlayer.Position)
			loadwalk:Play()
		else
			rig.Humanoid:MoveTo(rig.Parent.Start.Position)
			loadwalk:Play()
		end
	end
end

first, im not sure how to make it so that the animation wont keep on resting because its in a loop but im not sure how to constantly update where the nearest player is without doing that

second, eventualy if he plays the attack animation enough and the movetofinished just doesnt work anymore so he is constantly running to the player instead of attacking it.