How to do something on a delay after a button press in Swift but, postpone the delay each time the button is pressed?

82 Views Asked by At

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?

1

There are 1 best solutions below

2
mathAndCats On

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:

class ViewModel: ObservableObject {
    
    @Published var displayText = false
    
    var timer: Timer? = nil
    
    func setupTimer() {

        // "reset" the timer
        timer?.invalidate()
        
        // delays for 3 seconds
        timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { timer in
            self.displayText = true
        }
    }
}

struct View1: View {
    
    @StateObject var viewModel = ViewModel()
    
    var body: some View {
        
        VStack {
            if viewModel.displayText {
                Text("Delayed Display")
            }
            
            Text("Button to Start Delayed Display")
                .onTapGesture {
                    viewModel.setupTimer()
                }
        }
    }
}