Breaking loop instantly when value changes

Hello,
I have this script where I need long wait (60 seconds in this case), however I need to break the loop when the value changes even during the wait.

local Loop = false

script.Parent.Parent.Event:Connect(function()
	Loop = not Loop
end)

while Loop do
	wait(60)
	print("Finished")
end

For example when the wait has reached 37 and the value changes I need to break the loop instantly instead of waiting the remaining 23 seconds to check if the value has changed.

I’ve tried using coroutines and suspending them however that does not break the loop.

Thanks for any help.

1 Like
local Game = game
local RunService = Game:GetService("RunService")

local Flag = false

local function OnEvent()
	Flag = true
end

while true do
	local StartTime = RunService.Stepped:Wait()
	while true do
		local CurrentTime = RunService.Stepped:Wait()
		if CurrentTime - StartTime > 60 then break end
		if Flag then break end
	end
end

You’d need to connect the ‘OnEvent’ function to something.

1 Like

That doesn’t exactly help with my issue, the code will halt for 60 seconds anyways without checking the value.

while true do
	local StartTime = RunService.Stepped:Wait()
	while true do
		local CurrentTime = RunService.Stepped:Wait()
		if CurrentTime - StartTime > 60 then break end
		if Flag then break end
		wait(60)
		print("Finished")
	end
end

remove the wait(60) homie. u are yielding with .Stepped:Wait()

1 Like

He was implying that you’d fire OnEvent() when the value changed, thereby setting the flag to “true” and terminating the loop. If you would like to do this in the same loop, you can create a variable that stores the old value of the value and contrast it with the current value of the value in an “if” statement to see if it has changed.

1 Like