Hey, so I’ve heard a lot of controversy regarding the wait() keyword. I threw together some pseudocode for when I really need my code to yield. Is this any better than using wait() directly? I’ve also heard it said using the :Wait() method of classes is more efficient, like on an event.
Here’s what I threw together:
local function Yield(seconds)
local elapsed = tick()
while (tick() - elapsed) < seconds do
game["Run Service"].Stepped:Wait() --//Better?
end
end
:Wait() over wait() is referring to being event based, instead of polling. Using events is usually preferable; ex: instead of checking if x is true every frame, resume a thread when x is set to true.
Another issue with wait is the thread scheduler, when the thread scheduler spends >1ms resuming threads, it stops resuming threads until the next frame. If this is an issue, you may want to implement wait yourself.
Although since you never return deltaTime, I assume you don’t use it. Re implementing wait doesn’t fix the issue of timing not being entirely precise, so deltaTime should be returned (and used, when timing is important).
local RunService = game:GetService"RunService"
local Stepped = RunService.Stepped
local function Yield(s)
local t = tick()
while tick()-t < s do Stepped:Wait() end
return tick()-t
end
Yes - it avoids possible situations where the Roblox scheduler runs slow.
That being said, for larger wait times it tends to be less of an issue, and if you need perfect precision, you’ll likely opt for something more complex, but generally this is a good idea.