[Module] Managed Connection

Simple module which creates ManagedConnection instances for control event spamming

API
local RunService = game:GetService("RunService")
local ManagedConnection = require(-<pathToManagedConnection>-)

local NewConnection = ManagedConnection.newConnect(RunService.PreRender, function(Delta) 
	print(Delta)
end, 1)

print(NewConnection.Connection.Connected) -- NewConnection.Connection is RBXScriptConnection

NewConnection.DebounceTime = 1
NewConnection.Function = function(Delta)
	print("Skibidi")
end

NewConnection:SetCondition(function(Delta)
	return Delta % 5 == 0
end)
NewConnection:SetCondition()

NewConnection:Disconnect()
Source code
local ManagedConnection = {__metatable = "table: 0x52fcfd59c8a04fcc"}
ManagedConnection.__index = ManagedConnection

function ManagedConnection.newConnect(Signal: RBXScriptSignal, Function: (any) -> any, DebounceTime: number?): ManagedConnection
	local self = setmetatable({}, ManagedConnection)
	self.DebounceTime = DebounceTime
	self.Function = Function
	
	self.Connection = Signal:Connect(function(...)
		self:_HandleSignal(...)
	end)
	
	return self
end

function ManagedConnection:_HandleSignal(...)
	if self.DebounceTime and self.DebounceTime > 0 then
		if self._lastInvocationTime and (os.clock() - self._lastInvocationTime) <= self.DebounceTime then return
		else self._lastInvocationTime = os.clock() end
	end

	if typeof(self._Condition) == "function" and not self._Condition(...) then return end

	self.Function(...)
end

function ManagedConnection:SetCondition(Condition: (any) -> boolean)
	self._Condition = Condition
end

function ManagedConnection:Disconnect()
	if typeof(self.Connection) == "RBXScriptConnection" then
		self.Connection:Disconnect()
	end
	
	self.Connection = nil
	self._lastInvocationTime = nil
end

return ManagedConnection

Suggest your ideas for new features! :white_check_mark: