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.
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()
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.