Waiting event for a certain time?

--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.

7 Likes