I need help adding a cooldown

So long story short when i spam click buy button it keeps buying and my money becomes negative

game.ReplicatedStorage.Add.OnServerEvent:Connect(function(player, Amount, maxAmount, button, text, click, amt)
	button.MouseButton1Click:Connect(function()
		wait(0.4)
		if player.Speed.Value == maxAmount then
			text.Text = "Max"
			return "Max"
		end
		
		if player.leaderstats.Coins.Value >= Amount then
			wait(0.4)
			Amount = Amount * 1.25
			task.wait(0.5)
			player.leaderstats.Coins.Value = player.leaderstats.Coins.Value - Amount
			player.Speed.Value += 1
			player.Character.Humanoid.WalkSpeed = player.Character.Humanoid.WalkSpeed + 1.25
			text.Text = "Buy for: "..Amount
			amt.Text = player.Speed.Value..'/'..maxAmount
			task.wait(0.5)
		end
	end)
	
	click.MouseButton1Click:Connect(function()
		task.wait(0.5)
		player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
	end)
	
	while true do
		task.wait(1)

		if player.Speed.Value == maxAmount then
			text.Text = "Max"
			return "Max"
		else
			text.Text = "Buy for: "..Amount
			amt.Text = player.Speed.Value..'/'..maxAmount
		end
	end
end)

You could add a table which keeps track of all active transactions.

local activeTransactions = {}

game.ReplicatedStorage.Add.OnServerEvent:Connect(function(player, Amount, maxAmount, button, text, click, amt)
	button.MouseButton1Click:Connect(function()
		if table.find(activeTransactions, player) then return end -- Player has an active transaction
		table.insert(activeTransactions, player)
		wait(0.4)
		if player.Speed.Value == maxAmount then
			text.Text = "Max"
			return "Max"
		end
		
	if player.leaderstats.Coins.Value >= Amount then
			wait(0.4)
			Amount = Amount * 1.25
			task.wait(0.5)
			player.leaderstats.Coins.Value = player.leaderstats.Coins.Value - Amount
			player.Speed.Value += 1
			player.Character.Humanoid.WalkSpeed = player.Character.Humanoid.WalkSpeed + 1.25
			text.Text = "Buy for: "..Amount
			amt.Text = player.Speed.Value..'/'..maxAmount
			task.wait(0.5)
		end
		table.remove(activeTransactions, table.find(activeTransactions, player)) -- Remove it from table
	end)
1 Like