Search code examples
swiftxcodecountdowntimer

How can I automatically restart a timer when time runs out?


I am trying to have a countdown start and once it hits 0 automatically restart the timer back at 10. I feel like this should be pretty simple but I am having issues.

@IBOutlet weak var timerLabel: UILabel!

var defaultTime = 10
var timer = Timer()

func startTimerFunc() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}

@IBAction func startTimerBtn(_ sender: UIButton) {
    startTimerFunc()
}

func resetTimer() {
    timer.invalidate()
    defaultTime = 0
}

@objc func action() {

    defaultTime -= 1
    timerLabel.text = String(defaultTime)

    if timerLabel.text == "0" {
        resetTimer()
        startTimerFunc()
    }
}

Solution

  • The timer keeps running until you invalidate it, Here you just need to reset the defaultTime:

    @objc func action() {
        if defaultTime == 0 {
            defaultTime = 10
        }
        defaultTime -= 1
        timerLabel.text = String(defaultTime)
    }