When scripting, I start to run into the same problem where when I call functions from clicks and I need to wait before running the code, I only want the current function to run (for example, if the user spam clicks and multiple functions are called, I only want the most recent function to run, cancelling the previous ones).
Let's say when clicked, I wanted a text button's text size to turn 30, wait(5), then turn back to it's original size, 14.
textButton.MouseButton1Click:Connect(function() textButton.TextSize = 30 wait(5) textButton.TextSize = 14 end)
The problem is if the user only waited 4 seconds, then clicked it again, it wouldn't wait another 5 seconds, it would turn the size into 14 after 1 second because the previous function is still running. I want to make it so if a function is still running when a new one is called, the function that was running gets cancelled. This way if the user spam clicks, only the last click would count. It's kind of the opposite of a debounce if you think about it, I don't want only the first click to count, but the last one.
I've tried maaaaaaany different if-statements, and I've resolved this problem in the past using funky stuff, but I know there's definitely an easier way and I'm probably over-thinking it.
This is the correct way to do it:
local i = 0 --Index i function lastClick() local v = 0 --Indexing v v = i --Set v equal to i wait(5) if v == i then --If v is still equal to i after 5 seconds, then... textButton.TextSize = 14 --Set text size equal to 14 else --If not, then... return --Nevermind, forget it. Let the next execution worry about what happens next. end end textButton.MouseButton1Click:Connect(function() textButton.TextSize = 30 --Sets text size equal to 30 i = i + 1 --Increases i by 1 for each click lastClick() end)
Try this:
local Cancel = false local ClickCount = 0 textButton.MouseButton1Click:Connect(function() if ClickCount == 0 then -- this if statement will determine to cancel the function on the second click ClickCount = 1 Cancel = false elseif ClickCount == 1 then ClickCount = 0 Cancel = true end textButton.TextSize = 30 for i = 0, 5, 1 do -- basically wait(5) but broken down to segments (like wait(1) wait(1) etc.) if Cancel then textButton.TextSize = 30 return end wait(1) end textButton.TextSize = 14 end)