How to wait for event to fire with timeout?

At the moment, I am working on a pathfinding AI agent. I noticed that it gets stuck sometimes. This happens because it keeps waiting until it hits a certain waypoint. My agent waits until the event Humanoid.MoveToFinished fires and then continues his path. In some cases though, this never happens because it is completely stuck. So somehow I need to detect this and maybe update the agent’s path.

So I thought, what if I can set a timeout for Humanoid.MoveToFinished:Wait(). This way, I can detect if it is stuck. The issue is that I have not really come up with a nice way of coding this. How can I wait for either an event to fire or some delay to time out?

I thought of maybe wrapping the idea in a promise, so that I can use a then and catch if it fires or times out. An actual implementation of this idea is still missing though.

You could keep a record of the last position and check maybe every minute or so if that position has changed.

1 Like

This does not work in cases where the agent is moving without making progress (for example if it is standing on a conveyor belt).

You can achieve this with Promise.race, Promise.race resolves or rejects with the first promise that resolves/rejects.

Here’s a pretty simple example based on what you requested

local Promise = require( PATH.TO.PROMISE )

local TimeOut = 5

local function WaitForEvent(Humanoid)
	return Promise.new(function(Resolve, Reject, OnCancel)	
		Resolve(Humanoid.MoveToFinished:Wait())
	end)
end

local function WaitForTimeOut()
	return Promise.new(function(Resolve, Reject, OnCancel)
		task.wait(TimeOut)
		Reject("Timed Out")
	end)
end

local Promises = {
	WaitForEvent();
	WaitForTimeOut()
}

--Promise.race resolves with the first promise that was resolved or rejected
--Read more about it here: https://eryn.io/roblox-lua-promise/api/Promise#race
Promise.race(Promises):andThen(function(Result)
        --The event was a success!!
	--Do Stuff
end):catch(function(Err)
	if Err == "Timed Out" then
		--The event timed out do stuff
	else
		--Another issue occured
	end
end)
1 Like

Oh, this is exactly what I need. I did not even know about the race function. Good stuff!

1 Like