如何调用Timer()在1秒内快速调用30个计时器

时间:2018-11-22 06:34:34

标签: swift

var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:Selector("videosecondcounter"), userInfo: nil, repeats: true)

我想在1秒内调用30次计时器,请帮助我

1 个答案:

答案 0 :(得分:0)

这样,您可以在1秒内运行计时器30次。运行30次后,它将自动停止

// Timer That will be monitored
var myTimerToRepeat:Timer?
/// Number of times Timer ran
private var myTimerRunCount:Int?
/// Number of times Timer need to Run
private var numOfRepeatition:Int?
/// Time Interval for how long timer need to run
var myTimeInterval : TimeInterval = 1


/// Timer Handler
@objc func repeatTimerValue() {
    myTimerRunCount!+=1
    print("Repeat Count \(myTimerRunCount!)")
    /// Check is Timer Ran Max ?
    if myTimerRunCount! == self.numOfRepeatition! {
        /// yes Stop
        myTimerToRepeat!.invalidate()
        myTimerToRepeat=nil
    }
}

/// Start Timer
func startTimer(WithInterval Inter: TimeInterval) {
    if myTimerToRepeat != nil {
        myTimerToRepeat!.invalidate()
        myTimerToRepeat=nil
    }
        /// Start Timer
        myTimerToRepeat = Timer.scheduledTimer(timeInterval: Inter, target: self, selector: #selector(repeatTimerValue), userInfo: nil, repeats: true)
    }


override func viewDidLoad() {
    super.viewDidLoad()
    /// Set Count to 0
    myTimerRunCount=0
    /// Set the num of Repeatitions
    numOfRepeatition=30
    /// Start Timer
    startTimer(WithInterval: myTimeInterval/Double(numOfRepeatition!))
    }