Did I fix my loop spawning multiple times properly?

My power charge/decrease loop was basically spawning multiple times if you press it between the task.wait(0.125) period, I was wondering if this is the right way to fix it by just cancelling the thread or is there a simpler way because I feel like I’ve had this problem before

local ContextActionService = game:GetService("ContextActionService")
local Players = game:GetService("Players")

local localPlayer = Players.LocalPlayer
localPlayer:SetAttribute("Power", 20) -- Remove this later?

local updatingPower = false
local powerThread = nil

ContextActionService:BindAction("IncreasePower", function(actionName, inputState)
	if inputState == Enum.UserInputState.Begin then
		if updatingPower then
			return
		end
		
		updatingPower = true
		
		powerThread = task.spawn(function()
			while updatingPower do
				local newPower = math.clamp(localPlayer:GetAttribute("Power") + 5, 20, 75)
				localPlayer:SetAttribute("Power", newPower)
				
				task.wait(0.125)
			end
		end)
	elseif inputState == Enum.UserInputState.End then
		updatingPower = false
		
		if powerThread then
			task.cancel(powerThread)
		end
	end
end, false, Enum.KeyCode.E)

ContextActionService:BindAction("DecreasePower", function(actionName, inputState)
	if inputState == Enum.UserInputState.Begin then
		if updatingPower then
			return
		end

		updatingPower = true

		powerThread = task.spawn(function()
			while updatingPower do
				local newPower = math.clamp(localPlayer:GetAttribute("Power") - 5, 20, 75)
				localPlayer:SetAttribute("Power", newPower)

				task.wait(0.125)
			end
		end)
	elseif inputState == Enum.UserInputState.End then
		updatingPower = false
		
		if powerThread then
			task.cancel(powerThread)
		end
	end
end, false, Enum.KeyCode.Q)

-- Debugging
localPlayer:GetAttributeChangedSignal("Power"):Connect(function()
	print(`Power: {localPlayer:GetAttribute("Power")}`)
end)
1 Like