How do you cancel a for loop immediately?

So the method I usually use for cancelling a loop is along the lines of this example:

local bool = false
for i = 1,30 do
if bool then break end
wait(1)
end

This works, but it will occasionally wait 1 second before breaking the loop. How can I completely stop this from looping?

I’ve seen other scripts like intermission scripts where it’ll countdown, but say the max amount of players decreases it will completely cancel what it was doing without any latency.

local bool = false
for i = 1,30 do
	if bool then
		break
	else
		wait(1)
	end
end

Yes, but the script’s still going to wait 1 second before going back to the top of the loop and checking if the bool is true.

I want to cancel that wait(1) completely, how can I do that?

I’m not really sure what you mean. The if statement isn’t even needed as ‘break’ ends it immediately.

What’s the use-case for this? It would be better to use a BindableEvent for it if you can. If you really couldn’t then why not just do wait() or use RunService.Heartbeat?

I think it depends on what the loop is doing. In your case I don’t think its possible. You are using the loop to wait 30 seconds in one second intervals. There are many other ways to do this. I’m not sure what the best is but a couple alternatives:

Use the clock, tick() and increase your loop frequency. Use elapsed time or the bool/break to end your loop.

Use an event based wait. You could run a delayed function that waits 30 seconds, then fires the event(if it hasn’t been fired already), while the other function that could possibly change your bool variable is also running and possibly firing the event first (if bool hasn’t been changed).

A good thread explaining the use of the event based solution is here.

I might be foolish but shouldn’t you just replace “wait(1)” with “wait()”?

Then he would lose his 30 second timer.

I’ve got no clue what he’s trying to do. The closest thing to removing the 1 second interval before breaking the loop is the wait command. I can only hope that he will find his answer somewhere around here.

It’s impossible to get rid of the occasional one second wait, but we can shorten it down.

local bool = false
for i = 1,300 do
if bool then break end
wait(.1)
end

In this scenario, the occasional one second is now one tenth of a second.

You can get rid of it, but not with a wait()
see this:

so, it might look something like this, I don’t know if this works or not:

local bool = false
local YouMayContinue = Instance.new("BindableEvent")
--... some code doing stuff that might change bool and fire event...

delay(30, function()   --30 second delay function that doesn't yield the script
if not bool then YouMayContinue:Fire(0) end
end)

YouMayContinue.Event:Wait()    --script yields here until event is fired either by the delayed function or whatever other code you are running that triggered the break