How would I break this loop?

Hi, I’m trying to make a minigame where there will be a random number from 1 - 9 and you have to turn the handle the correct times. To confirm your turns you wait 4 seconds. And ofc I want the timer to reset every time you click the handle again, but I can not make this work. If you click the handle two times the loop/timer will run twice at the same time. So I have to break the loop somehow, but I do not know how?

local function countTime()		
	confirmTime = 0
	
	repeat wait(1)
		confirmTime += 1
	until confirmTime == 4
	
	getTurns()
end

click.MouseClick:Connect(function()
	turnHandle()
	countTime()			
end)

You could do this with some kind of “generation” variable that ticks up every time you click.

Then you’d check that the current generation matches the one when the loop started:

local gen = 0
local function countTime()
  gen += 1
  local myGen = gen
  confirmTime = 0

  repeat wait(1)
    confirmTime += 1
  until confirmTime == 4 or gen != myGen

  if gen == myGen then
    getTurns()
  end
end

Alternatively, ditch the slow loop idea. All “clicking” does is sets some “last clicked time” variable.

Then have a separate renderstep loop that always runs, and compares the current time to the “last clicked time”. If that’s more than 4 seconds, trigger getTurns

I am not sure how to implement this, I have tried but it did not work.

local clickCount = 0

local function countTime()
	clickCount += 1
	local newClick = clickCount
	confirmTime = 0
	
	repeat wait(1)
		confirmTime += 1
	until confirmTime == 4 or newClick ~= clickCount
	
	getTurns()
end

My post included an example implementation
It’s the same as yours but you have to guard the final getTurns call inside an if as well

1 Like