While conditional loop causing lag?

I was using a while loop to delay a part of a script

while tick() - lastick < 30.5 do
if not char:IsDescendantOf(game) then
       break
end
if tick() - lastick >= 30 then
      -- what the script will do when conditional is done, I have this because if i put the rest of the script under this while loop and the other conditional breaks the loop it will error
      break
end
RService.Heartbeat:Wait()
end

lastick gets updated so that it resets my timer if needed be, however this is lagging my game. I’ve reached this conclusion because I’ve checked script performance, but I don’t know why it lags my game. I think it may be that its constantly calculating tick - lastick which causes lag, but this shouldn’t be performance heavy right?

3 Likes

Why not remove the while condition check if you’re already checking for it inside the loop itself?

Tried that didn’t change anything

Is this being run cross server or locally? Also while loops for me have always sucked no matter the condition and I try to avoid them. If I am correct (kind of a beginner scripter heh) you might want to consider using a loop under RunService not sure if this applies though.

If you mean, A to run a while loop under a heartbeat event, then that would lead to a memory leak cause you would start a new while loop per frame. B, if you mean to use the conditional under heartbeat and disconnect it later, then that would be the same thing basically, no?

Not really knowledgeable on memory leaks so I cant say for sure, now for your second part I think I was talking about RunService.RenderStepped though I think that would effect the actual timer on the local side for users?

Its being ran on server per player

Have you tried putting print(“n”,tick()) where n is a number to indicate the print location in the code and tick gives you the time it reached that print.
Might help finding where the lag is.

I already found the source of lag and fixed it, thanks for the help though

Would you care to share what you found so others may know how to resolve similar problems?

It was the rate I was checking the if statement, I was running the loop 60 times a second and that wasn’t needed because I’m checking if I delayed the script for 30 seconds. Replacing the heartbeat with a wait(1) fixed it.

1 Like