Help with ending a loop

Hello,

I don’t think my brain is quite working correctly, and so I am loosing my mind trying to work out how I can stop a loop from running.

Code
local FlagData = require(script.Parent.Modules.Data.FlagData)

local function SetFlag(Part, FlagType)
	--[[
		Function to set a given flag part to a given flag type- if the part does not have a SurfaceGui setup inside it, it will automatically add
		one for it.
	]]

	if not FlagData then return end

	local function HasInstance(instance, list)
		--[[
			Function used to check if an instance within a list of instances is a certain instance type.
		]]

		for _, V in pairs(list) do
			if not V:IsA(instance) then 
				return false
			else
				return true
			end
		end
	end

	local PartChildren = Part:GetChildren()

	if not HasInstance("SurfaceGui", PartChildren) then
		local SurfaceGui = Instance.new("SurfaceGui")
		SurfaceGui.Face = "Top"
		SurfaceGui.ResetOnSpawn = false
		SurfaceGui.Parent = Part
	end

	local SurfaceGuiChildren = Part.SurfaceGui:GetChildren()

	if not HasInstance("ImageLabel", SurfaceGuiChildren) then
		local ImageLabel = Instance.new("ImageLabel")
		ImageLabel.Size = UDim2.new(1, 0,1, 0)
		ImageLabel.BackgroundTransparency = 1
		ImageLabel.Parent = Part.SurfaceGui
	end

	if FlagData[FlagType] then
		print(FlagType .. " active on " .. Part.Name)
		if #FlagData[FlagType] > 1 then
			while true do
				Part.SurfaceGui.ImageLabel.Image = "rbxassetid://" .. FlagData[FlagType][1]
				wait(0.25)
				Part.SurfaceGui.ImageLabel.Image = "rbxassetid://" .. FlagData[FlagType][2]
				wait(0.25)
			end
		else
			while true do
				Part.SurfaceGui.ImageLabel.Image = "rbxassetid://" .. FlagData[FlagType][1]
				wait(0.25)
				Part.SurfaceGui.ImageLabel.Image = "rbxassetid://0"
				wait(0.25)
			end
		end
	elseif FlagType == "Off" then
		print("Ended") -- Stop the loops from running above
	else
		warn("FlagSystem Error - Something tried to activate a flag on '" .. Part.Name .. "', but the given flag type does not exist.")
	end
end

SetFlag(workspace.Flags_V2.MSector1_Flag, "Safety Car")
wait(5)
SetFlag(workspace.Flags_V2.MSector1_Flag, "Off")

I’m trying to make whichever loop is running, stop running when ‘FlagType’ is equal to off. If you can read and understand my code, I’d really appreciate your help with this.

Thanks

(Also feel free to offer any other improvement tips)

You haven’t checked if the FlagType is off in the while loops.

Run the loops inside different threads with task.spawn(so they wont pause script execution) and store the threads inside a variable outside the SetFlag function(as an array). Then when FlagType is set to false run a loop and kill all the threads using task.cancel, then after killing them remove them from the array.

I keep getting the error task.cancel is not enabled do you have any idea what this could mean?