What is delay used for?

So I was just scripting functions for fun and then I found one function that caught my eye. It was named “delay”, and I didn’t know how to use the function. I tried searching the web but there were no descriptions to fix the problem. So I’ve decided to ask you guys for help about this.

You may show examples if you want to!

7 Likes

delay(time, func) makes a new thread in a manner most similar to spawn and runs that thread after time seconds. You can find more information about globals on the wiki.

4 Likes

delay is used for, as the name implies, to delay the call of the function provided given for the given amount of seconds, without interrupting the current thread.

delay(5, function(dt)
    print("Hi!", dt)
end)

print("Hello!")

This will print "Hello!" first, since the first function is called in a separate thread after roughly five seconds. delay also passes the actual time waited, similar to spawn and wait

20 Likes

Also I believe delay was more accurate than wait

1 Like

im not really sure about that. Try this

local time = 1
local repeats = 5
local start
for i = 1, repeats do
	start = tick()
	delay(time, function()
		print(tick() - start)
	end)
	wait(time)
	print(tick() - start)
end
1 Like

You shouldn’t use delay or spawn. Use coroutines.

coroutine.resume(coroutine.create(function()
    wait(4) -- Does the exact same thing as delay

    print("Hello world")
end))

Delay does the exact same thing as above. It creates a new thread but waits before running the function passed.

4 Likes

yes that is true, but I think he was just asking what is delay since he saw it

1 Like

The global function delay takes 2 arguments: first is a time to wait in seconds, the second is the function to call after the wait time has elapsed, delay continues executing unlike wait which blocks.

local function Test()
print'This is actually cool!'
end;

delay(3, Test);

print'This ran first!'

why is coroutines considered better practice than delay or spawn?

They are both in Roblox’s 30hz pipeline, and there is no guarantee that they will run. Read more here:

https://eryn.io/gist/3db84579866c099cdd5bb2ff37947cec

3 Likes