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

How would I go around firing a function on delay that also can be reset?

Asked by
Lolnox 47
5 years ago

So for example I have a function x that I want to fire after 5 seconds pass which I would achieve with this simple line:

delay(5, x())

But my dumb head struggles to come up with a way to "reset the timer". As in, for example you click on a button that makes the said timer reset to its initial value so it waits for the whole 5 seconds again after which it'll finally fire the function.

2 answers

Log in to vote
0
Answered by
kazeks123 195
5 years ago
Edited 5 years ago

Well, then I guess you'll have to simply put your x() after a while loop with a variable that will be reset every time you press a button:

local player = game.Players.LocalPlayer
local button = player.PlayerGui.ScreenGui.Frame.Button

local timer = 5

button.MouseButton1Down:Connect(function()
    timer = 5
end)

function aaa ()
    while timer > 0 do
        timer = timer - 1
        wait(1) --It's important to wait after we decrement timer variable, so that player would still be able to cancel function call during the last second
    end

    x()
end


aaa()
0
Sorry, my wording wasn't clear enough, I need the button to prevent the function from being fired by resetting the delay timer back to 5 seconds. Lolnox 47 — 5y
0
Just updated my answer to suit your needs. kazeks123 195 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

Something like this works:

local UserInputService = game:GetService("UserInputService")

local functionId = 0

local function DoStuff(id)
    if id ~= functionId then return end

    print("Successfully ran function")
end

UserInputService.InputBegan:Connect(function(input, gameProcessed)
    if input.UserInputType == Enum.UserInputType.Keyboard then
        if input.KeyCode == Enum.KeyCode.T then
            local currentId = functionId + 1
            functionId = functionId + 1
            delay(2, function()
                DoStuff(currentId)
            end)
        end
    end
end)

The idea is you keep track of an id variable which gets passed in to your function. Every time the delay is triggered, you increment the id. Then in the DoStuff function, if the passed in id doesn't match the current functionId, exit out. This way, every time you call the delay before the last one fires, it acts as if the timer is reset, as only the last call to delay will activate.

Answer this question