Is there a better way to implement a custom event timeout?

Right now, I have a function that waits for an event to occur, and returns the event connection parameters. However, if the event does not occur within a specified length of time, the function stops waiting for the event and returns nil.

Here is my function:

function Utility.ConnectEventWithTimeout(event, timeout_length)
	local bindable_event = Instance.new("BindableEvent")
	
	-- Fire BindableEvent with event data when called
	local connection = event:Connect(function(...)
		bindable_event:Fire(...)
	end)
	
	-- Cause a timeout if event has not been fired within `timeout_length`
	delay(timeout_length or 5, function()
		if not bindable_event then
			return
		end
		bindable_event:Fire()
	end)
	
	-- Yeld until result or timeout
	local result = bindable_event.Event:Wait()
	connection:Disconnect()
	connection = nil
	bindable_event:Destroy()
	bindable_event = nil
	return result
end

This works perfectly for all practical purposes. However, as far as I know, there is no effective way to kill the created thread once the event has occurred before the timeout length, so it keeps waiting, possibly for a very long time, effectively wasting resources. My main concern is unnecessary memory use over time, especially with long timeout lengths, or in my main use case, hundreds of NPCs running this function for an event (not pretty).
Any ideas? :slight_smile: