How to Pause and Resume a Timer in Swift

Timers are a vital component in Swift for scheduling tasks at specified intervals. While starting a timer is straightforward, there may be scenarios in your app where you need to pause and then resume it. In this article, we’ll explore how to pause and resume a timer in Swift, offering solutions for more advanced timing functionality.

Pause and Resume Functionality

To implement pause and resume functionality for a timer in Swift, you can follow these steps:

Initialize the Timer: Create a timer as you normally would. In this example, we create a timer that fires every 1 second:

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

Pause the Timer: To pause the timer, you’ll need to use a mechanism to stop it temporarily. You can invalidate the timer:

timer.invalidate()

Resume the Timer: To resume the timer, you’ll need to create a new timer. The original timer cannot be restarted once invalidated. Recreate it as follows:

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

Remember to adjust the time interval and any other properties to match your original timer’s settings.

Advanced Pause and Resume

For more advanced pause and resume functionality, you can encapsulate the timer management in a custom class. This allows you to keep track of the timer’s state and manage it more effectively. Here’s a basic outline of a custom timer manager:

class TimerManager {
    private var timer: Timer?
    private var isPaused: Bool = false

    func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }

    func pauseTimer() {
        timer?.invalidate()
        isPaused = true
    }

    func resumeTimer() {
        if isPaused {
            startTimer()
            isPaused = false
        }
    }
    
    @objc func timerAction() {
        // Your timer action code here
    }
}

This TimerManager class allows you to start, pause, and resume the timer with more control.

Conclusion

In Swift, managing timers efficiently is crucial for applications with timing requirements. You can pause and resume timers using standard methods or create a custom timer manager class for more control. The choice depends on your project’s complexity and needs.

A pat on the back !!