快速点击按钮时的时间间隔更短

问题描述

我成功地为单击按钮创建了一个计时器。单击第一个按钮时,时间间隔恰好为一秒。但是当我按下另一个与相同 IBAction 功能配对的按钮时,时间间隔变短了。本质上,每按下一个按钮,时间间隔就会越来越短。

为什么会发生这种情况,我该如何解决

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
        }
    }
    
}

解决方法

因为每次点击按钮时,都会创建另一个计时器。

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

所以一段时间后,你有很多计时器,所有计时器都以随机间隔启动,并且都在触发。

所以想想会发生什么。例如,如果第二个计时器恰好是在第一个计时器触发的中间创建的,那么现在它们两个一起每半秒触发一次!等等。

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