Break loops immediately as soon as condition met

Basically, when a player clicks their mouse button, while ‘CanCatch’ is true, it sets ‘Catching’ to true. However, they have to wait the 3 seconds before the code continues.

-- Random wait for fish to appear
while not Catching do
	local RandomWait = math.random(3, 7)
	wait(RandomWait)
	print('Allowed to catch')
	CanCatch = true
	
	wait(3)
	
	CanCatch = false
end

print('Player is catching fish!')

So how can I quickly break this without doing something like this

if Catching then break end
wait(0.5)
if Catching then break end
wait(0.5)
if Catching then break end
wait(0.5)
if Catching then break end
wait(0.5)
if Catching then break end
wait(0.5)
if Catching then break end
wait(0.5)

Use tick() and do a repeat loop every RenderStepped or so, and if catching or tick() is greater than oldtick + 3 then you can catch.

Not entirely sure how I’d set that up tho?

It’s quite easy, like I explained.

local CurrentTick = tick() + 3
repeat RunService.RenderStepped:Wait() until tick() > NewTick or Catching

What’s ‘NewTick’?
30 chars30 chars30 chars30 chars30 chars30 chars30 chars30 chars30 chars30 chars

1 Like

Using wait() is not recommended, but you can use repeat loop to achieve it:

local start_tick = tick()
repeat wait() until Catching or tick() > start_tick + 3
if Catching then break end

You can use RunService.RenderStepped:Wait() if this is something rendering-related.
Or RunService.Heartbeat:Wait() if this is something not-so-related-with-rendering.

My bad, it’s a code inconsistency. Replace NewTick with CurrentTick.