How to teleport player after a certain distance?

Why does this work and how to make it?

code:

local character = script.Parent
local player = game.Players:GetPlayerFromCharacter(character)
local teleportdistance  = 100
while wait(1) do
	for _,v in pairs(game.Players:GetPlayers()) do
		if v.Name ~= player.Name then
			local playerdistance = player.Character.HumanoidRootPart.Position
			local otherplayerdistance = v.Character.HumanoidRootPart.Position
			local distance = (playerdistance - otherplayerdistance).Magnitude
			if distance < teleportdistance then
				teleportdistance = distance
				player.Character.Humanoid:MoveTo(otherplayerdistance)
			end
		end
	end
end