How do I instantly break a For Loop with a long wait()?

So I have a For Loop that runs a function every 20 seconds, but I want to be able to Instantly break the loop at any time without it finishing. I want to effectively destroy the loop.

The problem is the Wait(20) because it continues the thread.

for _,V in ipairs(RandomTable) do
    DoSomething()
    Task.Wait(20)
    DoSomethingElse()
    print("Finished")
end

You could create your loop in a different thread using task.spawn.

-- create the loop in a different thread and run it
local thread = task.spawn(function() 
	for _,V in ipairs(RandomTable) do
		DoSomething()
		task.wait(20)
		DoSomethingElse()
		print("Finished")
	end
end)


-- wait(for some time)
-- using task.cancel to stop the thread
task.cancel(thread)
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.