How do i make proper hitboxes?

I’m currently using this for hitboxes, and it works well but it has an issue that it delays the script that calls it until the duration is up. this is because of the while loop waiting for a target, but if i were to remove it, then it can’t find a target at all. This wouldn’t be a problem but it significantly delays the animation’s and delays damaging the target. is there any way i can fix this?

function module.CreateHitbox(Size, Duration, Cframe, char, isAOE)
	local connection
	local overlap = OverlapParams.new()
	overlap.MaxParts = 100
	overlap.FilterType = Enum.RaycastFilterType.Include
	overlap.FilterDescendantsInstances = workspace.Enemies:GetChildren()
	
	
	-- visual
	local hitbox = Instance.new("Part")
	hitbox.Parent = workspace
	hitbox.Size = Size
	hitbox.CFrame = Cframe
	hitbox.Anchored = true
	hitbox.Transparency = 0.5
	hitbox.BrickColor = BrickColor.new("Really red")
	hitbox.CanCollide = false
	game.Debris:AddItem(hitbox, Duration)

	local damagedTargets = {}
	local detectedTargets = {}

	connection = runservice.Heartbeat:Connect(function()
		local hitParts = workspace:GetPartBoundsInBox(Cframe, Size, overlap)
		for _, part in ipairs(hitParts) do
			if not damagedTargets[part.Parent] and part.Parent ~= char then
				damagedTargets[part.Parent] = true
				table.insert(detectedTargets, part.Parent)
				if not isAOE then
					break
				end
			end
		end
	end)

	local startTime = os.clock()
	while os.clock() - startTime < Duration do
		if #detectedTargets > 0 then
			break
		end
		runservice.Heartbeat:Wait()
	end

	connection:Disconnect()

	if isAOE then
		return detectedTargets
	else
		return detectedTargets[1]
	end
end

Well you’re yielding on the main thread with RunService.Heartbeat:Wait(). In my hitbox system I just use something like task.delay(lifetime, cleanup), and the cleanup function will first make sure the heartbeat isn’t already cancelled before trying to disconnect it.