How do npc follow but when out of limit he back to his place

hi i want some help with this problem is my npc follow player but i want do npc have limit when he research the limit he back to his place and if it tp it will be so good
this my script

local ATTACK_RANGE = 2.5
local CanAttack = false
local attacking = false
local Combo = 1
local DoingCombo = 0

local Hum = script.Parent:WaitForChild("Humanoid")
local FX = script:WaitForChild("FX")
local TweenService = game:GetService("TweenService")

local Anims = script.Parent:WaitForChild("Anims")
local Attack1Anim = Hum:LoadAnimation(Anims:WaitForChild("Attack1"))
local Attack2Anim = Hum:LoadAnimation(Anims:WaitForChild("Attack2"))
local Attack3Anim = Hum:LoadAnimation(Anims:WaitForChild("Attack3"))
local Attack4Anim = Hum:LoadAnimation(Anims:WaitForChild("Attack4"))




	

local InsertDisabled = function(Target,Time)
	local Disabled = Instance.new("BoolValue",Target)
	Disabled.Name = "Disabled"
	game.Debris:AddItem(Disabled,Time)
end	

local target = nil

local function runToTarget()
	local targetPosition = (script.Parent.HumanoidRootPart.Position - target.Position).Unit * (ATTACK_RANGE - 1) + target.Position
	script.Parent.HumanoidRootPart.CFrame = CFrame.lookAt(script.Parent.HumanoidRootPart.Position,target.Position)

	script.Parent.Humanoid:MoveTo(targetPosition) 
end

Use an if statement to detect if the target is out of range

local range = 50 -- change range here
local originalpos = CFrame.new(50,0,50) -- pos you want the humanoid to tp to (in CFrame)
local function runToTarget()
	local targetPosition = (script.Parent.HumanoidRootPart.Position - target.Position).Unit * (ATTACK_RANGE - 1) + target.Position
	script.Parent.HumanoidRootPart.CFrame = CFrame.lookAt(script.Parent.HumanoidRootPart.Position,target.Position)
    if (targetPosition - script.Parent.HumanoidRootPart.Position).Magnitude > range then
        script.Parent.HumanoidRootPart.CFrame = originalpos
    else
        script.Parent.Humanoid:MoveTo(targetPosition)  -- target is in range
    end
	
end