How would I add some sort of delay to clicking a button?

Once again, I am not great at scripting. So bare with me here.

Basically I looked up a tutorial on how to create a moving part. And when you click a button it moves.
But I wan’t to make it to where users cannot spam it and has a cooldown when clicked.

Heres the script.

part = script.Parent.Button
door = script.Parent.Door

function Open()
	for i = 1, 90 do
		door.CFrame = door.CFrame + Vector3.new(0,-.1,0)
		wait(.001)
	end
	
	wait(2.5)
	
	for i = 1, 90 do
		door.CFrame = door.CFrame + Vector3.new(0,.1,0)
		wait(.001)
	end
end

part.ClickDetector.MouseClick:connect(Open)

Again, not super great a scripting. If I could get some help or redirected to where I would learn how to do this that would be nice! Thank you!

You can add what’s known as a debounce. Like so:

local d = false;

local func = function()
    if d == true then return end

    d = true;

    — function

    wait();
    d = false;
end
1 Like
part = script.Parent.Button
door = script.Parent.Door
Debounce = false
DebounceTime = 3 -- The cooldown time

function Open()
   if not Debounce then
      Debounce = true
      for i = 1, 90 do
	     door.CFrame = door.CFrame + Vector3.new(0,-.1,0)
	     wait(.001)
      end

      wait(2.5)

    for i = 1, 90 do
     	door.CFrame = door.CFrame + Vector3.new(0,.1,0)
	    wait(.001)
    end

    wait(DebounceTime)
    Debounce = false

  end

end

part.ClickDetector.MouseClick:connect(Open)
1 Like

No this is incorrect because it doesn’t debounce. Your program is just a Boolean flipper/toggler.

Edit: Fixed :+1:

1 Like

Loop Alternative


Have you ever considered using TweenService? It eliminates the rapid looping at least.

1 Like

Instead of calling wait with the debounce time, the best way to do it is like so:

local COOLDOWN_TIME = 3
local lastOpened = 0

function openDoor()
  if tick() - lastOpened > COOLDOWN_TIME then
    lastOpened = tick()
    --code
  end
end

You should also consider using TweenService for the animation. Your wait(0.001) will wait a minimum of 0.03 seconds, not 0.001 seconds, and it’s generally just bad to use wait for an operation like this

10 Likes