Why is this task running in the main thread in a task.spawn()?

I have an ‘Auto ___’ feature in my game, and I’m trying to have it disable and enable while the auto feature runs, but it won’t disable while the auto feature runs. Here is the code:

autoButton.MouseButton1Down:Connect(function()
		if marketplaceService:UserOwnsGamePassAsync(localPlr.UserId, autoId) then
			if inGame then return end
			
			isInAuto = not isInAuto
			print(isInAuto)
			
			if isInAuto then
				task.spawn(function()
					while isInAuto do
						
						local wager = wagerBox.Text
						local mines = minesBox.Text
						local aog = tonumber(amountOfGuesses.Text)

						self:startGame(mines, wager)

						local already = {}
						for _ = 1, aog do
							task.wait(0.5)
							local guess
							guess, already = getTrueGuess(already)
							if self:trySlot(guess) ~= 'good' then
								break
							end
						end

						self:cashout()
						task.wait(1)
					end
				end)
			end

			
		else
			marketplaceService:PromptGamePassPurchase(localPlr, autoId)
		end
	end)

Specifically in the for loop does the ability to click the button in order to change the status of the ‘isInAuto’ variable. May someone help me? Happy Thanksgiving.

If I understood your problem correctly, just check before each loop if the “isInAuto” variable is true
The change:

for _ = 1, aog do
    if not isInAuto do
      print("isInAuto is false")
      return false
    end

	task.wait(0.5)
	local guess
	guess, already = getTrueGuess(already)
	if self:trySlot(guess) ~= 'good' then
		break
	end
end

Thanks for the reply, but this won’t work because the script can’t detect if the button is being pressed during the for loop. Where I try printing the isInAuto bool, it doesn’t print while the for loop runs. Therefore trying to check if it changed (even though it can’t) in the for loop can’t do anything.

This issue has more to do with the threads (processes). I try making a new thread though using task.spawn(), but that doesn’t seem to work (kind of).