How to correctly make a timer script

Hello everyone im trying to make a timer script. What this timer script should do is to display the seconds and minutes of the players 2x exp remaining. Everything works as intended but if the player buys more exp, the 2x exp starts going down twice as fast. If they buy more it goes down 3x as fast and i was wondering if their was a way to do this without causing the 2x exp to go down faster the more you buy it. I think its from the value changing multiple times theirfore it subtracts multiple times

script

local ExpTime = script.Parent
local player = game.Players.LocalPlayer

local StatTime = player.Stats.GymTime

local label = script.Parent
local stats = player:WaitForChild("Stats")
local ExpTime = stats:WaitForChild("ExpTime")
local expdebounce = false


if ExpTime.Value > 0 then
	expdebounce = true
end

function formatTime(input)
	
	local output
	
	if type(input) ~= "number" or input < 0 then 
		
		output = "--:--"
		
	else
		
		local formatString = "%i:%.2i" 
        local seconds = math.floor(input % 60)
		local minutes = math.floor(input / 60) 
		
		output = formatString:format(minutes, seconds)
		
	end
	
	return output
	
end
	 
ExpTime.Changed:connect(function()
	
	expdebounce = true
	local timeString = formatTime(ExpTime.Value)
	
	
	spawn(function()
		if ExpTime.Value > 0 then
				wait(1)
			ExpTime.Value = ExpTime.Value - 1
			
			else
			
			expdebounce = false
			
		end
	end)
	
if timeString then
        label.Text = "2x Exp Remaining: " ..timeString
    end
end)

When player buys it second time 2x exp It does make the next spawn function to spawn. And so on
if they player buys it thirth time there are 3 spawned functions running.

ExpTime.Changed:connect(function()
	expdebounce = true
	local timeString = formatTime(ExpTime.Value)
	if ExpTime.Value == 0 then
		spawn(function()
			if ExpTime.Value > 0 then
				wait(1)
				ExpTime.Value = ExpTime.Value - 1
			else
				expdebounce = false
			end
		end)
	end
	if timeString then
		label.Text = "2x Exp Remaining: " ..timeString
	end
end)
1 Like