How to stop repeat function from lagging?

Hi, I want to know how I can stop this repeat function from lagging the game every time it subtracts a coin from a intvalue inside the player?

When I go to start the game and basically press the activation key for the code, all of the coins suddenly go away and the game lags very bad.

I feel like I am using it wrong, but i dont really know what is going on.
The script down below is being used in ServerScriptService.

    local playr = game.Players.LocalPlayer
	local coins = playr:WaitForChild("Coins")
	
	repeat
		wait(1)
		coins .Value = coins .Value - 1
	until
	coins .Value == 0

Any help here to make it better I guess? Thank you.

1 Like

How often are you running the code?
Did you check for errors? (script exhausted allowed execution time is a common error that can occur if you have while true loops without task.wait in them)
I need a little bit more code in order to determine how to fix this.
(Side note: task.wait() is more accurate than wait(), you might want to use that instead)

First of all you can’t use the LocalPlayer object in server script service. You must use a playeradded event with the player argument. Here is some improved code:


    local players = game.Players
	local coins = playr:WaitForChild("Coins")

    players.PlayerAdded:Connect(function()
        repeat
		task.wait(1)
		coins.Value -= 1
        until coins.Value == 0
    end)
1 Like

here is the full code it is not much but yeah

coinSubtractor.OnServerEvent:Connect(function()
	
	local playr = game.Players.LocalPlayer
	local coins = playr:WaitForChild("Coins")

	repeat
		wait(1)
		coins .Value = coins .Value - 1
	until
	coins .Value == 0
	
end)

Fixed your code a bit.

game.Players.PlayerAdded:Connect(function(Plr)
    local coins = Plr:WaitForChild("Coins")

    repeat
        task.wait(1)
        coins.Value -= 1
    until coins.Value == 0
coinSubtractor.OnServerEvent:Connect(function(playr) -- remote events give the player, dont need to pass the player as an argument from the local script firing it
	local coins = playr:WaitForChild("Coins")

	repeat
		task.wait(1)
		coins.Value -= 1
	until coins.Value == 0
end)

I decided to just do everything all over again and I put the subtraction code into a local script, it works fine now. Sorry for the disturbance.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.