Should I be fine using wait(n) here?

Right now I am making a system where I award a player points every second.

I have read a thread where it says that using wait(n) or wait() is bad when it is available to use Event listeners.

while true do 
     wait(1)
     --award points
end 

Is it a bad practice and are there any risks of using wait(n) here such as the code being delayed?

Alternatively to make sure everything is executed promptly, you can use Heartbeat:Wait() which essentially listens for the event “firing”.

while true do 
     local elapsed = 0
     repeat
           elapsed+=Heartbeat:Wait()
     until elapsed >= 1
     
     --award points
end

Which should I use for this case? Are they both fine to use and am I stressing too much about wait(n)?

If you’re waiting for large intervals (like in terms of whole seconds) it’s fine to use wait. If whatever you are doing is really dependent on timing then you can use the number returned from the call to wait() - that is the exact amount of time that the code yielded.

2 Likes

I’m guessing you’re talking about the article Avoiding wait() and why? The article was generally going over why the use of wait() and values that are so small that are comparable to wait(), such as wait(0.01) should generally be avoided. It doesn’t really matter for larger numbers, such as 1. But if you’re still wanting to have a Custom wait, there was one in the DevForums for that.

Tl;dr, thearticle doesn’t really apply for large numbers like 1, it was going over the reasons wait() and wait(0.01) or anything small basically should be avoided, it’s fine to use wait for large numbers

2 Likes

I see. Thank you for confirming.

1 Like

I do not really get this method. Could you maybe explain differently? Do you mean using deltatime from the runservice events to find the time that has elapsed?

You should be fine, but an alternative to the while true loop would be:

local timeValue = 0
game:GetService("RunService").Stepped:Connect(function(et, deltaTime)
  timeValue += deltaTime
  if timeValue >= 1 then
    timeValue = 0
    -- run your code here, should NOT yield
  end 
end)
2 Likes

Yes this is similar to my second method but using the event instead of a loop. Thank you.

1 Like