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):
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
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

wait()

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

Answer this question