Wait() pausing "for <> do" functions

I’ve been searching for a while and couldn’t find anything on this, most likely because I’m terrible at searching for things. I may not describe this very well, so apologies for that.

I’m trying to pause the script without pausing for i = 0, 10, 1 do, eg. create an object in all children, then remove it 1 second later, without stopping the whole script, or using :GetChildren() to delete them all.

for i = 0, 10, 1 do
-- create object
wait(1)
-- delete object
end

So far everything I’ve tried, coroutines and tasks, will still continue to pause the entire function. (Admittedly, I barely have any idea on how they work, but so far they seem to get pretty close to working, they just pause when I do task.wait(), or anything else involving waiting.)

task.delay() creates a new thread that starts after the time that is put into the first parameter ends.

for i = 0, 10, 1 do
	--//Create object
	task.delay(1, function()
		--//Delete object
	end)
end
1 Like

Debris:AddItem is probably your best solution. It will destroy the passed Instance after the passed amount of seconds without yielding/pausing.

local DB = game:GetService("Debris")

for _ = 1, 10 do
	local NewInstance = nil -- create object
	
	DB:AddItem(NewInstance, 1)
end
1 Like

I feel a bit stupid for not figuring this out until now, but it worked, so thank you.

I tested this as well, and it worked good for the example I used, but I was using deleting objects as an example. I might find a use for it later.

Debris also uses the old wait(n) instead of task.wait(n) which is why you should use task.delay instead.

1 Like