boehmatron boehmatron -3 years ago 72
Swift Question

timer wont start with start/pause toggle button

I want to make a timer that gets triggered by one button to start the timer. When the timer is running, I want the same button to pause the timer.

I handle this behaviour mainly within the IBAction of the button label:

@IBAction func btn_start(_ sender: Any) {
if timerIsRunning == false {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
timerIsRunning = true
}

if timerIsRunning == true {
timer.invalidate()
timerIsRunning = false
}
}


I recognized that I can trigger the start button several times and the timer was triggered also severalt times, so that the timer was speeding up in the end.
To prevent this behaviour I introduced the timerIsRunning:Bool with the unexpected result, that the timer does not start anymore :-/

This is my timer function that is triggered by the timer:

func runTimer() {
if timeInSeconds >= 0 {
timeInSeconds = timeInSeconds - 1
updateTimerLabel()
}
}


Can anyone explain this? and give me a helping hand?

Answer Source

You should return after you start the timer, or use else. Otherwise you always invalidate the newly created timer instantly in the second if block in your method:

@IBAction func btn_start(_ sender: Any) {        
    if !timerIsRunning {        
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)            
        timerIsRunning = true                       
    } else {            
        timer.invalidate()            
        timerIsRunning = false            
    }        
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download