How can I prevent stutters when transferring Network Ownership?

Hi DevForum,

The title is pretty self explanatory, I just want to know how I can easily transfer Network Ownership of a soccer ball from one player to another without it stuttering/freezing mid air.

Here’s the code:

local ball = script.Parent  -- Reference to the soccer ball
local players = game:GetService("Players")

local function setBallOwnership()
	local nearestPlayer = nil
	local shortestDistance = 30

	for _, player in pairs(players:GetPlayers()) do
		local character = player.Character
		if character then
			local distance = (character.PrimaryPart.Position - ball.Position).Magnitude
			if distance < shortestDistance then
				nearestPlayer = player
				shortestDistance = distance
			end
		end
	end

	if nearestPlayer then
		ball:SetNetworkOwner(nearestPlayer)
		print(nearestPlayer)
	else
		ball:SetNetworkOwner(nil) 
	end
end

game:GetService("RunService").Heartbeat:Connect(setBallOwnership)