Why do the time intervals between each second become shorter every time the button is clicked?

67 Views Asked by At

I successfully created a timer for when buttons are clicked. When the first button is clicked, the time intervals are exactly at one second. But the moment I pressed another button that is paired with the same IBAction function, the time intervals get shorter. Essentially, after every button pressed, the time intervals get shorter and shorter.

Why is this occurring and how can I solve this?

import UIKit

class ViewController: UIViewController {
    //var eggTimes : [String: Int] = ["Soft": 5, "Medium":7, "Hard":12]
    
    let eggTimes = ["Soft": 300, "Medium":420, "Hard":720]
    var timer = 0;
    
    @IBAction func buttonClicked(_ sender: UIButton) {
        let hardness = sender.currentTitle!
        timer = eggTimes[hardness]!
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    @objc func updateCounter(){
        if timer > 0 {
            print("\(timer) left for perfectly boiled egg!")
            timer -= 1
        }
    }
    
}
1

There are 1 best solutions below

0
matt On BEST ANSWER

Because every time you tap the button, you create another timer.

@IBAction func buttonClicked(_ sender: UIButton) {
    // ...
    Timer.scheduledTimer(//... makes a new timer
}

So after a while you have many timers, all started at random intervals, and all firing.

So think about what happens. If the second timer, for instance, happens to be created half way between firings of the first, now together the two of them fire every half second! And so on.

Tap: x   x   x   x ... every second
Tap:       x   x   ... every second, on the half second
Tap:            x  ... every second, on the quarter second