Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 8 years ago

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

2 answers

Log in to vote
1
Answered by 8 years ago

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):
01function foo()
02    if debounce then return end --If debounce is true, stop the function without doing anything
03    local debounce = true
04 
05    print("Hello, world")
06    --Do some stuff Here
07 
08    wait(1) --Wait 1 second
09 
10    debounce = false --Make the function callable again
11end
12 
13foo() --Prints "Hello, world"
14foo() -- 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:

01local lastCalled = 0
02function foo()
03    if tick() - lastCalled < 1 then return end --Do nothing if 1 second has not passed
04    lastCalled = tick()
05 
06    print("Hello, world")
07    --Do stuff here
08end
09 
10foo() -- Prints "Hello, world"
11foo() -- Again, does nothing because 1 second has not yet elapsed
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. RubenKan 3615 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

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

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

Answer this question