After a few hours of a server being active, I get chat lag in my game and I think I have found the problem but I’m not sure.
I have a while loop when the player joins the game to give them cash every second but I want to know if that loop still runs when the player has left.
If so, how can I break the loop when they leave?
game.Players.PlayerAdded:Connect(function(plr)
while task.wait(1) do
if game.Players:FindFirstChild(plr.Name) then
plr.leaderstats.Cash.Value += 1
else
break
end
end
end)
This is an incredibly ineffecient method. You don’t even have to check if a player has joined the game. You can just create a single while loop that will iterate through a table of the players currently in the game. Also, your while loop won’t account for potential lag. You can connect a function to RunService | Roblox Creator Documentation instead. You an do it like this:
local Players = game:GetService("Players")
local CASH_ADDED = 1 -- setting for the amount of cash added after each delay
local CASH_DELAY = 1 -- setting for the delay in seconds until cash is added
local t = 0 -- the elapsed time
game:GetService("RunService").Heartbeat:Connect(function(deltaTime)
t += deltaTime
if t >= CASH_DELAY then
t -= CASH_DELAY
for _,player in pairs(Players:GetPlayers()) do
player.leaderstats.Cash.Value += CASH_ADDED
end
end
end)
Well, as I stated earlier, the reason I do it like this is to account for lag that can potentially happen.
If the server lags then it will throttle. With a while loop this means that it will resume once the server resumes. However, all the seconds that passed, even if it was only a single one, will pass with players not being awarded the cash they are entitled to for their time spent. However, using RunService | Roblox Creator Documentation, the deltaTime parameter for the connected function will return the time that has passed since the last iteration. If lag happens, then this can go from it normally ranging from 0.01 to 0.04 seconds in-between each iteration to pretty much anything larger. It all depends on how long the server is throttled.
Given a theoretical scenario where 10 seconds passed since the last iteration, our t value will now be at or above 10. Now, as I’m sure you noticed, it doesn’t immediately remove 10 on the step. It will instead steadily reduce this by 1 until it is less than 1.
how would this work if you wanted a specific player to get cash after spending 10 minutes in-game? it seems with this method it’s giving everyone cash indiscriminately. I would like it so players can’t hop from server to server and get cash in the “server’s” 10 minute time frame, but it be 10 minutes starting the moment that specific player joins the game.