How to Instantly Break a While Loop on Value Change?

I’m making a simple script for police lights using a while loop and functions as shown below.

However, when trying to shut off the lights, the script has to run through whats left of the light pattern before shutting off. This will be a problem when I add longer and more advanced light patterns. How would I instantly break the while loop when the value changes?

I tried looking for some solutions online but found none.

local status = script.Parent.Status

status.Changed:Connect(function()
	if status.Value == true then
		while status.Value == true do
				allBlues() -- Turns on all blue lights
				wait(.4)
				allReds() -- Turns on all red lights
				wait(.4)
			end
		
	elseif status.Value == false then
		while status.Value == false do
			allOff() -- Turns off all lights
			wait(.5)
		end
	end
end)

You could probably do something like this:

local status = script.Parent.Status

status.Changed:Connect(function()
	if status.Value then -- true
		repeat allBlues()
		wait(0.4)
		if status.Value then
			allReds()
			wait(0.4)
		end
		until not status.Value
	else -- false
		allOff()
	end
end)

3 Likes

If you’re wanting the break to become instant, I would highly suggest on making it more checked upon when the functions are playing out. Here’s what I would do:

local status = script.Parent.Status

status.Changed:Connect(function()
	if status.Value == true then
	
	    local breakValue = false
	
	    while true do
		    print("allblues")
		    if breakValue == true then break end
		    wait(.4)
		    if breakValue == true then break end
		    wait(.4)
	    end
    else
	    print("all off")
	end
end)
1 Like