Creating an efficient Timeout for :Wait()

I have to make a pathfinder script, and in the script, I have to implement a Timeout for functions, something similar as how :WaitForChild() works, it would wait for a child, and with an argument to set a Timeout.

I came out with a solution:

local Zombie = game.Workspace.Zombie

local TimeoutEnd = Instance.new("BoolValue")
local Timeout = 5

coroutine.resume(coroutine.create(function()
	wait(Timeout)
	if not TimeoutEnd then
		TimeoutEnd.Value = true
		print("Timeout! MoveToFinished didn't fire.")
	end
end))

coroutine.resume(coroutine.create(function()
	Zombie.Humanoid.MoveToFinished:Wait()
	if not TimeoutEnd then
		TimeoutEnd.Value = true
		print("Zombie finished moving! It finished moving before the maximum time.")
	end
end))

TimeoutEnd:GetPropertyChangedSignal("Value"):Wait() --// Waiting for signal.
TimeoutEnd:Destroy()

RandomFunctionAfterTimeout()

However, I’m not sure if there’s a better way to make this, I have to implement this with probably around 20-30 NPCs, and I have to fire every second.

I just found one thread talking about this, sadly, the solutions aren’t using the best practices.

Is there a better way to make this? Thanks for reading.

You can use a module script to these functions or you can easily use on a NPC template.

Could you explain this? I’m kind of confused.

You can create a NPC model as a template and clone it whenever you need it.

I believe what you want to do can be achieved with the following piece of code: Timeout argument for Event:Wait() - #4 by Merely

You can pathfind using my module. You can easily set a timeout and also this module runs one loop for the timeout per rig per path using custom wait by PysephDev. You can view the source code of the module if you need more info.