Is there a less messy way of adding debounce/cooldowns to actions?

Hey, I’ve been trying to find a way to add cooldowns between actions/moves with a less messy and cluttered way (REfering to debounce btw :broken_heart:).

Here’s my current way of adding cooldowns between actions

Is there anything I could do to make this less messy and use less lines of code?

1 Like

Sadly there isn’t. I’ve thought of any other way of optimizing it but the only thing you could do if you’d like to optimize would be to change “double kick” to a number which would be less readable for you but a bit faster for the system to run if the table has a lot of values.

[EDIT]
Oh wait… you could just check if states.active = true or false.

2 Likes

Your underlying logic is fine and probably won’t get any easier. You could always make a function for it though to break it out of your action handler:

local function Cooldown(name, duration)
   cooldowns[name] = true
   task.delay(duration, function()
      cooldowns[name] = false
   end)
end

-- From your task
if inp.KeyCode == Enum.KeyCode.E then
   if cooldowns["double kick"] then return end
   Cooldown("double kick", 5)
   task.wait(1)
   states.active = false
end

Of course, that requires you to make sure it’s not set already, or else the function will step on a previously called one.

You could get even fancier and pass a closure function to the cooldown function that only gets called if the cooldown isn’t set:

local function Cooldown(name, duration, callback)
   if cooldowns[name] then return end
   cooldowns[name] = true
   task.delay(duration, function()
      cooldowns[name] = false
      callback()
   end)
end

-- From your task
if inp.KeyCode == Enum.KeyCode.E then
   Cooldown("double kick", 5, function()
      task.wait(1)
      states.active = false
   end)
end
4 Likes

THank you brah this actually makes adding cooldowns way less messy :broken_heart:

1 Like

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