What is delay/task.delay used for?

I’ve just been wondering about delay/task.delay.

These are the things I want to know about it:

  • What is it?
  • How do you use it?
  • Is it different from wait/task.wait? If so how?
  • Should it be used often?
  • What instances should it be used in?
1 Like

I personally don’t use it but its essentially a different version of

task.defer(function()
    task.wait(n)
    -- code here
end)

with the exception that it can also take coroutine threads instead of functions I believe, for the most part though its just personal preference on which one you want to use

1 Like

This might be helpful:

3 Likes

The Roblox exclusive global “delay” is the outdated version, the task library function “delay” is the current version. Its use is relatively simple, you pass to it two arguments, the first a number value & the second a function value (functions are values in Lua), this first argument represents the length of time which should elapse before the second argument is called. It is very much different from the global “wait” and the task library function “wait” as those functions yield whereas delay/task.delay does not, take a look at the following example.

task.wait(1)
--Code here is delayed for 1 second.
print("Hello world.")
--After 1 second passes the print function is called.

task.delay(1, function()
	print("Hello world!")
end)
--Code here executes immediately.
--After 1 second passes the print function is called.

task.delay(1, print, 1)
--This is the same as the previous example.
--Code here executes immediately.
--After 1 second passes the print function is called.

The functions wait/task.wait yield because they instruct the current thread of execution (the one which is handling the execution of the script) to wait (as its namesake suggests) for some length of time before continuing again. The functions delay/task.delay do not yield because they create an additional thread of execution (one which is external to the main thread handling the execution of the script), due to this the main thread can continue with its execution without disruption. The additional thread is delayed for some length of time before its function is called, once the execution of this function has concluded/resolved the additional thread is closed.

Regarding when & how often you use delay/task.delay, that is entirely up to you, hopefully this tutorial has provided you with the information necessary to make those decisions yourself.

3 Likes

Is it new? It sounds op that u can just replace heartbeat wait and coroutine like that