Is this method of yielding any better than wait()?

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

Thanks.

I think it is, if you read this article:

You might find a part where this guy who made this article, mentioned that you can use :Wait(), an example he gave, was using Stepped:Wait():

I hope this helps you.

3 Likes

This is totally fine; I use this myself. As long as you’re not busy-waiting (freezing the game for some set period of time) you can’t go too wrong.

1 Like

Do you think it’d be a better practice to use something like this versus using wait() directly??

wait isn’t a keyword.

: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
2 Likes

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.

1 Like

I see. Thanks for all the great info guys, I appreciate it.