Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make a function pause a certain amount of seconds before being able to be called again?

The title says it all. It's probably a really stupid question with an obvious answer.

2 answers

There are two ways you can do this.

  1. Create a bool value that is set to true when the function begins and set back to false when it finishes (often called a debounce):
function foo()
	if debounce then return end --If debounce is true, stop the function without doing anything
	local debounce = true

	print("Hello, world")
	--Do some stuff Here

	wait(1) --Wait 1 second
	
	debounce = false --Make the function callable again
end

foo() --Prints "Hello, world"
foo() -- Does nothing because 1 second has not yet elapsed

The second way is to store the time the function was last called, and return if not enough time has elapsed yet:

local lastCalled = 0
function foo()
	if tick() - lastCalled < 1 then return end --Do nothing if 1 second has not passed
	lastCalled = tick()

	print("Hello, world")
	--Do stuff here
end

foo() -- Prints "Hello, world"
foo() -- Again, does nothing because 1 second has not yet elapsed

1 comment

0

Calling a normal function with a wait() in it will yield the thread, so the first one will print hello world 2ce, just with a one seccond delay! If it was fired via a :Connect event, then that would work. Not like this.

It depends how long to you want it to wait if you want it to wait a certain amount of seconds just say

wait()

The amount of time would go into the to parenthesis. :)

This discussion is preserved as it was. New answers, comments, and votes are closed.