So we use :Wait() to wait for an event, but I want this with a timeout like it will wait 2 seconds then continue doesn’t matter it fired or not, how can I do that?
--if timeout is nil it defaults to 5(basically how much to wait for response)
--dt is the amount of wait between each check, if nil then it's the minimum
function waitEvent(event: RBXScriptSignal, timeout: number?, dt: number?): ...any
timeout = timeout or 5
local start = os.clock()
local connection, data, done
connection = event:Connect(function(...)
data, done = {...}, true
connection:Disconnect()
end)
repeat task.wait(dt) until done or (os.clock()-start > timeout)
if not done then connection:Disconnect() return nil end
return table.unpack(data)
end
local response = waitEvent(game.Players.PlayerAdded, 10)
print(response)
PS: there may be a better way to achieve this, I am open to discussion.
Unfortunately, there’s no way to do that, the way I can think is right after I connect the event, i spawned a new thread or coroutine which waits for 2 second before disconnecting the connection.
That works but it will yield the entire script because of the connection. You should spawn a new thread to settle this if you want to continue execute the script.
That’s correct, I assumed the creator wants to wait until they get a response.
task.defer() or task.delay(), allternatively the global delay() also exists.
I think that’s the purpose, yielding the main thread until some data has loaded.
Don’t use that, it’s going to get deprecated later down the line and suffers from a number of issues including how it’s reliant on a legacy pipeline. It’s not an alternative anymore and you should always be using delay from the task library if you need delay. Delay is dangerous and should be avoided.
See this Gist:
https://eryn.io/gist/3db84579866c099cdd5bb2ff37947cec
I’m aware, hence I suggested the task library version first, I was just making the original poster aware of its existence.