Debounce for ContextActionService

So I am playing around with ContextActionService and I wanted to add a delay, it works after I press K and it waits for 1 second. However, if I spam K, the debounce gets broken and doesnt wait at all. What should I do? And if my code has any room for improvements/more efficient ways to do, please tell me! I am trying to be better than yesterday.

local CAS = game:GetService("ContextActionService")

local map = script.Parent:FindFirstChild("main_map")
local inventory = script.Parent:FindFirstChild("main_inventory")

local function toggleMap(inputName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin then
		map.Enabled = true
	else
		map.Enabled = false
	end
end

local db = true
local function toggleInventory(inputName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin and db == true then
		db = false
		inventory.Enabled = true
	else
		inventory.Enabled = false
	end
	task.wait(1)
	db = true
end

--binds
CAS:BindAction("toggleMap", toggleMap, true, Enum.KeyCode.M)
CAS:BindAction("toggleInventory", toggleInventory, true, Enum.KeyCode.K)
1 Like

Solution:

if inputState == Enum.UserInputState.Begin and db == true then
		db = false
		inventory.Enabled = true
	    task.wait(1)
	    db = true
	else
		inventory.Enabled = false
	end

General Solution:

local ContextActionService = game:GetService("ContextActionService")

local debounce, pause, entries = false, nil, 0

local function action(_, inputState)

	if inputState == Enum.UserInputState.Begin then

		if debounce then return end
		debounce = true

		pause = true

		-- your code

		pause = false; debounce = false

	elseif inputState == Enum.UserInputState.End then
		
		entries += 1
		if entries > 1 then return end

		while pause do
			task.wait() -- keep your entry here until you pause turns false
		end

		-- your code			

		pause = true; entries = 0 
	end
end

ContextActionService:BindAction("Action", action, false, Enum.KeyCode.K)

--[[

Code Logic (Explanation): 

1. You press K or let go of K and the function is called
2. The input state is "Begin" when K is pressed
3. When K is let go of, the input state is "End"
4. Pressing and letting go of K runs the function twice
5. Adding a debounce for pressing K creates a cooldown
6. The cooldown is removed when the actions for pressing K have run
7. A condition that the actions for letting go of K only run when the actions for pressing K have completed, is created
8. A while loop was used with the condition to keep the first entry
9 Other entries are getting blocked for performance and consistency concerns
10. When the condition to keep the entry was broken, the actions for letting go of K ran
11. After these actions completed, the condition was reset for consistency and the entries were removed


]]

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.