I'm working on a Swift app that is listening for a button press, and n seconds after the button is last pressed I want to display an alert. But if a user spams the button before n seconds is up, I want to reset the delay back to n seconds on each button press without just displaying multiple alerts.
There are obviously ways to do something after a delay in Swift (using DispatchQueue or Timer, etc.), but I'm struggling to figure out how to 'extend' the delay if the button is pressed again before the delay of n seconds completes.
Has anyone dealt with this issue or have any suggestions for how to tackle this type of problem?
If you use a Timer for the delay, you can invalidate it each time, effectively resetting it. (I think you'll have to use a ViewModel for this, because you can't have a timer variable attached to a view.) Something like this: