How to find closest waypoint PATH?

Hello everyone!

So i’m currently making an pathfinding npc which goes to the closest waypoint with pathfinding and then removes from the list beacuse it’s got checked (and it won’t target that waypoint until he will check all waypoints on the map), but there’s problem…
If there’s waypoint behind the wall, it will be closest waypoint, but path isn’t actually closest. I tried to make function where script checks how many points npc needs to reach the target, and it works, except for thing it takes really long… I wrote print thing and it works not instantly, every pathfind game makes takes at least 0.1 second and my npc doesn’t going anywhere for that time.

Here’s script:

local function ClosestPoint(list)
	for i, waypoint2 in ipairs(list) do

		local path2 = PathfindingService:CreatePath(HumanoidProperties)
		if LastTarget == nil then
			path2:ComputeAsync(NPC.HumanoidRootPart.Position, waypoint2.Position)
		else
			path2:ComputeAsync(LastTarget.Position, waypoint2.Position)
		end	
		if path2.Status ~= Enum.PathStatus.NoPath then
			local WayPoints = path2:GetWaypoints()
			print(#WayPoints)
			table.insert(waypoints3, #WayPoints)
		end

	end
	for i, waypoint2 in ipairs(waypoints3) do
		if BestPointDistance ~= nil then
			if BestPointDistance < waypoint2 then
				BestPointDistance = waypoint2
				BestPoint = waypoint2
			end
		else
			BestPointDistance = waypoint2
			BestPoint = waypoint2
		end
	end
end

How do i fix delay when finding closest path with pathfinding?