How do I make this function run every 3 seconds?

The script below runs repeatedly even though I added a debounce for every 3 seconds. Is there a way to make it compatible with debounces?

local ContextActionService = game:GetService("ContextActionService")

local Tool = script.Parent

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

local debounce = false

function Dance()
	print("ran")
end

Tool.Equipped:Connect(function()
	if debounce then return end
	
	debounce = true
	ContextActionService:BindAction("Dance", Dance, false, Enum.KeyCode.Z)
	wait(3)
	debounce = false
end)

1 Like

You’re checking if the debounce is true, however you initially set it to false, so it’s not gonna Run the code.

Both the BindAction and equipped function fires despite there being a debounce.

Do you get what I meant? Initially, your debounce is false, however, you’re doing the checking to see if it’s true, so you should probably initially set it to true first, then set it to false while the code is running, then set it back to false when it’s done.

Check your debounce inside of the Dance() function.

local function dance()
    if not debounce then
        debounce = true
        print('Ran')
        wait(3)
        debounce = false
    end
end

Tool.Equipped:Connect(function()
	ContextActionService:BindAction('Dance', dance, false, Enum.KeyCode.Z)
end)

-- Also might want unbind the action when the tool is unequipped

Tool.Unequipped:Connect(function()
	ContextActionService:UnbindAction('Dance')
end)

@ItzMeZeus_IGotHacked Their script will return (“exit” the function) only if the debounce is truthy, else it will run as normal. Since false isn’t truthy, it isn’t going to return/exit the function.

3 Likes