Magnitude not working properly

So im making sliding door that opens when player get close to it.

The problem is when i stay at specific distance to it just keep opening and closing and i dont have any idea how to fix it.

I have a thought of adding debounce but dont know how to do it.

Here is the script and video.

local ts = game:GetService('TweenService')

local info = TweenInfo.new(0.2, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, 0, false, 0)

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		while true do
			wait(0.1)
			
			local distance = (char.HumanoidRootPart.Position - script.Parent:WaitForChild('Door1').PrimaryPart.Position).magnitude
			if distance < 7 then
				ts:Create(script.Parent:WaitForChild('Door1').PrimaryPart, info, {CFrame = CFrame.new(30.375, 4, -135.375)}):Play()
				ts:Create(script.Parent:WaitForChild('Door2').PrimaryPart, info, {CFrame = CFrame.new(39.625, 4, -135.375)}):Play()
			else
				ts:Create(script.Parent:WaitForChild('Door1').PrimaryPart, info, {CFrame = CFrame.new(34.875, 4, -135.375)}):Play()
				ts:Create(script.Parent:WaitForChild('Door2').PrimaryPart, info, {CFrame = CFrame.new(35.125, 4, -135.375)}):Play()
			end
		end
	end)
end)

(sorry i dont know how to make a video appear in window rather than a link)

robloxapp-20240524-1806498.wmv (387.8 KB)

ok first, do not use a loop for every player… just use 1 loop and check how far every player is from it

local LastDoorOpened = 0
local PlayerNearDoor = false
local Closed = true

while Door do
	PlayerNearDoor = false
	local Players = game.Players:GetPlayers()
	for i = 1, #Players do 
		if Players[i] and Players[i].Character and Players[i].Character:FindFirstChild('Torso') then 
			local distance = (Door.Door1.PrimaryPart.Position - Players[i].Character.Torso.Position).magnitude 
			if distance < 7 then
				-- someone at the door
				PlayerNearDoor = true
			end 			
		end 
	end
	if PlayerNearDoor and Closed and (tick() - LastDoorOpened) > 2 then -- 2 second open cooldown
		-- open door
		Closed = false
		LastDoorOpened = tick()
	elseif not Closed then
		Closed = true
		-- close door
	end
	task.wait(0.1)
end