Delay or debris timeout or wait(n)?

i really dont know the difference between using a wait(n) or delay(n,) or debris:AddItem(p,n) to destroy a part

delay(.5, function() --.5 -- idk better method? V V
		for i,v in pairs(p) do       --[[for i,v in pairs(p) do
			d:AddItem(v,0)                     d:Additem(v,0.5) end]]
		end                 -- or [[wait(.5) for i,v in pairs(p) do v:Destroy()]]????
	end)

which is better for performance, any help?

1 Like

Don’t do any of them, debris:additem() uses delay, spawn and delay have many issues because of the inbuilt wait.

Instead use coruninite.wrap() for creating a new thread, and RunService:Wait() for waiiting before destroying something

Here would be an good implementation:

function AddItem(Part, Time, CallBack, OnCancel) -- CallBack ONLY runs when AddItem destorys the item, not if the user destorys it
	local State = {Cancel = false}
	local Elapsed_Time = 0
	local Connection
		
	-- ill be using a psuedo thread system with .Heartbeat:Connect instead of creating an actual thread
	Connection = game:GetService('RunService').Heartbeat:Connect(function(T) 
		
		Elapsed_Time += T -- increase the elapsed time by the time passed before last update
		
		if State.Cancel == true then  -- ? Did use put Table.Cancel then let's immediatly cancel the removal
			Connection:Disconnect()
			if OnCancel then
				coroutine.wrap(OnCancel)(Elapsed_Time)
			end
			return
		elseif Part == nil then -- Part is nil? (Happens in rare cases) let's disconnect the hearbeat!
			Connection:Disconnect()
			return
		elseif Elapsed_Time >= Time then -- enough time has passed to remove the object? let's destory it!
			Connection:Disconnect()
			Part:Destroy()
			if CallBack then
				coroutine.wrap(CallBack)(Elapsed_Time)
			end
			return
		end
			
	end)
	
	return State
end

local State = AddItem(
	workspace.Baseplate, 
	5, 
	function(TotalTimeTaken)
		print(TotalTimeTaken)
		print 'LOL '
	end, 
	function(totalTimeTaken)
		print ('haha we made debris quit', "   ", totalTimeTaken)
	end
)


wait(2)
State.Cancel = true
3 Likes

Uh you don’t put wait(.5) you use runservice to create a custom implementation of wait(), like in the example above I showed you.

wait has issues in general that’s why I reccomond creating a custom implementation of wait() here would be a less beefed down version.

local function Wait(n)
	local Run = game:GetService('RunService')
	local TotalTime = 0-- we're gonna keep incrementing this every frame
	
	while true do
		local TimeFromPreviousFrame = Run.Heartbeat:Wait() -- Hearbeat:Wait() is better then wait and returns back time from previois frame
		TotalTime += TimeFromPreviousFrame
		
		if TotalTime > n then -- now we check, if enough time has passed to cancel the wait if yes we stop waiting
			return
		end
	end
end

Wait(10)
print 'lol'
3 Likes