Adding cooldown to button

Hey!
I’m trying to make a cooldown to a button. Once a player go to a specific marker, they have the option to press “X” to gather an item. However, I want to add a timer so they cannot spam “X”, and want that timer to be 10 seconds. I have tried to add a timer, however it doesn’t work properly. Right now, as the code is shown below, it keeps spamming “Cooldown for harvesting”.

My goal is to do the following:

  1. Player goes on marker and presses X (first time at marker). A countdown starts counting to 10, if the person presses X before the counter is finished, he’ll receive a message saying “Cooldown for harvesting” (using print).
  2. Once the timer is over, the person can press X again and it’ll execute what it is supposed to do. And obviously, the timer will start on new.

Here’s my code (only the timer I need help with, and how to trigger it once a player presses X):


local startTimer = true
Citizen.CreateThread(function()
    while true do
        Citizen.Wait(0)
        if CurrentAction ~= nil then
            SetTextComponentFormat('STRING')
            AddTextComponentString(CurrentActionMsg)
            DisplayHelpTextFromStringLabel(0, 0, 1, -1)

            if IsControlJustReleased(0, Keys["X"]) and startTimer then
				startTimer = false

				if CurrentAction == 'coke_harvest' then
                    TriggerServerEvent('esx_drugs:startHarvestCoke')
                end
                CurrentAction = nil
			
			else
			    print("Cooldown for harvesting drugs")
				ESX.ShowNotification('Cooldown')
			
            end
        end
    end
end)

Citizen.CreateThread(function()
	if not startTimer then
		local time = 10 -- 10 seconds
		while (time ~= 0) do -- Whist we have time to wait
		Wait( 1000 ) -- Wait a second
		time = time - 1
		-- 1 Second should have past by now
		end
	-- When the above loop has finished, 10 seconds should have passed. We can now do something
		startTimer = true 
	end
end)
1 Like