Infinitely Looping Function's Effect on Performance

Greetings! I’m looking to create a function repeatedly loops over and over again after some amount of time, while completing some actions at the end of the duration. I have accomplished it as follows:

function Protocol:InitiateStart()
    self.Timer:start(self.TurnTime)  --starting the objects timer
    self.Timer.finished:Wait()   --waiting till the objects timer finishes
    --print("Timer Ended")
    --complete some other logic, send events, etc.
    self:InitiateStart()   --recursively restarting the timer
end

Currently this works, but I have a concern that if this keeps running over and over again, it will cause performance issues over time. I feel like since the newly called self:InitiateStart() is “inside” of the other self:InitiateStart(), the code would sort of “pile up” as the server would have to go through all the “layers” of self:InitiateStart().

I don’t know if my concerns are actually valid or just me being paranoid, and I haven’t observed any noticeable effects yet.

However, will this be a concern if the function is in its 100th/1000th/10000th loop? Or is there another, more effective way, for me to go about this that doesn’t involve recursively calling the function.

1 Like

Hello,

You don’t need to worry about any issues cause by this.

Just make sure there isn’t too many things going on at the same time.

Hope this helps!

1 Like
function flow(r)
  if (r < 1) then return r end
  print("hello world")
  flow(r - 1)
end

-- flow(5)
1 Like

remember if you do too much recursion you will get the most legendary error, stack overflow :sunglasses:

1 Like

I’d feel a simple while true… loop here feels better than recursion

2 Likes

You will eventually cause a stack overflow by doing this.

1 Like

Oh my gosh how did I not think about that. Yes, I could’ve just done a simple while loop :grin:

1 Like