While loops for each playing on server still running after they've left

I found this problem yesterday when I was testing something, that this while loop still seems to run even after a player has left.

This gets required when the player joins the game

game.Players.PlayerAdded:Connect(function(player)
    require(script.RewardsManager)()
end)
-- RewardsManager
return function()
    -- Setup timed rewards (every 15 minutes)
    spawn(function()
        while wait(15 * 60) do
            local Reward = 20
            if GamepassCheck(player, 'VIP') then
                Reward = 30
                
                -- Chat message
                SystemMessage:FireAllClients(player.Name .. " just earnt $30 for being a VIP!", Color3.fromRGB(216, 166, 66))
            end
            
            TimedReward:FireClient(player, Reward)
            UpdateCash(player, Reward, false)
        end
    end)
end)

Now I noticed yesterday, that this

SystemMessage:FireAllClients(player.Name .. " just earnt $30 for being a VIP!", Color3.fromRGB(216, 166, 66))

Fired, even when the player wasn’t in game anymore (they had left like 5 minutes before) I know it was fired because this even leads to a message being displayed in the chat.

So does that mean while loop continue running on the server even after the player has left… And thus couldn’t this lead to lag issues when lots of players have joined/left in the same server?

1 Like

Maybe you break the loop once the player has left

1 Like

You can add if player == nil then break end like ivebeenterminated said.

Has @ivebeenterminated, you just have to break the loop when the player has left the game.

Script:

game.Players.PlayerAdded:Connect(function(player)
	require(script.Parent)(player)
end)

ModuleScript:

return function(player)
	spawn(function()
		while wait(5) do
			if game.Players:FindFirstChild(player.Name) then --Check if the player is still in-game
				
				-- your code
				
			else
				break --If the player is not in-game, break the loop
			end
		end
	end)
end

Tested the code and It works.