Is there a point to use wait() and why do you use wait?

wait() is mainly something I use a lot when I script something and really wanna know if there is a point in even using it

You must be a new scripter.

If you don’t want something to happen instantly, you use wait.

For example:

print "hi"
wait (3)
print "how are you"

I think that means that it will wait forever until the next part of the script happens, instead of waiting a set amount of time.

You usually use waits to avoid time outs.

--This will time out as it runs so fast
while true do
print("Hi!")
end

--This will not time out as it is waiting minimal time before next loop
while true do
wait()
print("Hi!")
end

It’s important to know when to use wait appropriately.

3 Likes

or you could do

while wait() do
    print("Hi")
end

both work the same

The purpose of the wait(n) method’s to have a thread sleep for a certain amount of time.
For example, you may have seen code that looks similar to this

while true do
    wait(1)
    print("Hello World!")
end

A while loop repeats specific code until the condition’s no longer met

Notice how Hello World appears in the output around every second since the script began running. It’s putting the thread to sleep for around 1 second before resuming and letting the thread continue.

wait(n) also returns the time that had elapsed since it was called, and the game’s running time.

local n, t = wait(1)
print(n) -- around 1
print(t) -- varies, usually following DistributedGameTime

Many programmers rely on this when they do while wait() do, which isn’t the best practice

If no wait time was provided to wait(n) (thus wait()), it will default to a minimum wait time of around 1/30 (or .0333…). Note that if wait(n) was given a number too low, it will instead default to 1/30 as well.

local n, t = wait()
print(n) -- around .0333
print(t) -- ditto

But because of how Lua’s task scheduler works, it may not always be the most reliable - it’s recommended that you use a custom wait for heavy usage of the method.

Here’s the link to the task scheduler - it’s an interesting read so I highly recommend checking it out.

I hope this helped. :slight_smile:

If you suppose run

while true do
    print("Hi")
end

Its a never ending loop. And its most likely to crash studio.

So we use

while wait() do
     print("Hi")
end

Which gives us a very small wait before executing the while loop again. This can be replaced and made more efficient with RunService

We use wait in a lot of different ways.
Suppose you want to make a GuiObject visible after 5 seconds and then make it invisible after 3 seconds. We do -

wait(5)
GuiObject.Visible = true
wait(3)
GuiObject.Visible = false

Suppose you are making a Round System for your game. It will surely need wait() in it.

wait() is pretty self explanatory. It puts a wait for the amount of seconds you chose. Example wait(5) this puts a wait for 5 seconds before executing the next lines of code.