Pathfinding issue

Hello guys !
Im having issues with a pathfinding system I found on youtube this tutorial

when im testing my game alone it works perfectly, but when I test it with other players it repeat an event until the player is out of range the npc

local function findNearestPlayer()
	local players = Players:GetPlayers()
	local nearestPlayer = nil
	local maxDistance = 50
	
	for _, plr in pairs(players) do
		if plr.Character ~= nil then
			local targetCharacter = plr.Character
			local distance = (NPC.HumanoidRootPart.Position - targetCharacter.HumanoidRootPart.Position).Magnitude
			if distance <= maxDistance and checkForCharacter(targetCharacter) and targetCharacter then
				nearestPlayer = targetCharacter
				--maxDistance = distance
				PlrString.Value = tostring(plr)
				if db == 0 then
					db = 1
					task.wait(0.1)
					JumpscareSound:FireClient(Players:GetPlayerFromCharacter(targetCharacter))
					FOVChasingRm:FireClient(game.Players:FindFirstChild(PlrString.Value))
					CamMove:FireClient(Players:GetPlayerFromCharacter(targetCharacter), NPC)
				end
			else
				if db == 1 then
					FOVNotChasingRm:FireClient(game.Players:FindFirstChild(PlrString.Value))
					PlrString.Value = ""
					db = 0
				end
			end
		end	
	end
	return nearestPlayer
end

here is the function, if you guys can help me i’ll really appreciate it, and if you need more informations

and here is a video to explain my problem

Try this


local PlayersInRange = {}

local function findNearestPlayer()
	local players = Players:GetPlayers()
	local nearestPlayer = nil
	local maxDistance = 50
	
	for _, plr in pairs(players) do
		if plr.Character ~= nil then
			local targetCharacter = plr.Character
			local distance = (NPC.HumanoidRootPart.Position - targetCharacter.HumanoidRootPart.Position).Magnitude
			
			if distance <= maxDistance and checkForCharacter(targetCharacter) then
				nearestPlayer = targetCharacter
				
				if not PlayersInRange[plr.UserId] then
					PlayersInRange[plr.UserId] = true
					JumpscareSound:FireClient(plr)
					FOVChasingRm:FireClient(plr)
					CamMove:FireClient(plr, NPC)
				end
			else
				if PlayersInRange[plr.UserId] then
					FOVNotChasingRm:FireClient(plr)
					PlayersInRange[plr.UserId] = false
				end
			end
		end	
	end
	
	return nearestPlayer
end