How do i yeald a thread for 5 seconds or untill a remote event is fired

I want for my server script to do something after 5 seconds or if a player fires a remote event, I know how to do both, but just not at the same time.

To verify, you’re trying to execute some code after 5 seconds pass, or if a RemoteEvent gets fired during that time period?

Maybe something like this:

local MAX_YIELD_TIME = 5 --//Time before the callback is executed naturally

local function onFlagCompletion() --//Execute code when some condition occurs
	print'yay'
end

local function yieldUntilFlag()
	local timeElapsed = 0

	local tempRemoteListener, tempUpdateListener;
	
	local function executeCallback() --//Clean up listeners and execute some callback
		tempRemoteListener:Disconnect()
		tempUpdateListener:Disconnect()
		
		onFlagCompletion()
	end
	
	--//Do something after yielding naturally
	tempUpdateListener = game:GetService("RunService").Heartbeat:Connect(function(dt)
		timeElapsed += dt

		if timeElapsed >= MAX_YIELD_TIME then
			executeCallback()
		end
	end)
	
	--//Or until a remote event gets fired
	tempRemoteListener = someRemote.OnServerEvent:Connect(executeCallback)
end
coroutine.wrap(yieldUntilFlag)()
1 Like

dont ya need a wait 1 in there somewhere

Try this:

local t = 5 -- or how ever many seconds you want
local target = tick() + t

local param1, param2, ... = nil, nil, ... -- have as many parameters as you want

spawn(function()
      param1, param2, ... = remoteEvent.OnServerEvent:Wait()
      target = tick()
end)

repeat wait() until target < tick()

--remote event fired, or t seconds passed

This will wait until the current time reaches the target time (the time it will be in 5 seconds)
When the remote event is fired, it sets the target to the current time so it ends.

What do you mean? I use a Heartbeat event to update a timer to determine when enough time has elapsed, and during that time period if the event gets fired it’ll execute the callback immediately.

There are many ways to do this. Here is a simpler way.

local flag = true

remoteEvent.OnServerEvent:Connect(function() -- your RemoteEvent
	flag = false
end)

counter = 0
while flag do
	task.wait(0.1)
	counter += 0.1
	if counter >= 5 then break end
end

print("hi")  -- your code here 

if you don’t want it to block your script you simply put it in a thread with task.spawn()

local Run = game:GetService("RunService")
local Replicated = game:GetService("ReplicatedStorage")
local RemoteEvent = Replicated.RemoteEvent

local Time = tick()
local Fired = false

local Event = RemoteEvent.OnServerEvent:Connect(function()
	Fired = true
end)

while true do
	Run.Heartbeat:Wait()
	if Fired then
		Event:Disconnect()
		print("Event fired!")
		break
	elseif tick() - Time >= 5 then
		print("Event timed out!")
		break
	end
end