BlueBear
BlueBear

Reputation: 23

Update Progress Bar every milliseconds

I want my Progress Bar to update every milliseconds. How would I do this? Currently, it updates every second, which is not what I want.

EDIT: Sorry, I forgot to mention that I still want the timer label to update every second (So it will go down by seconds not milliseconds: 10, 9, 8) while updating the progress bar every milliseconds or 25 times every second.

Code:

 progressBar.transform = progressBar.transform.scaledBy(x: 1, y: 5)
        progressBar.layer.cornerRadius = 5
        progressBar.clipsToBounds = true
        progressBar.layer.sublayers![1].cornerRadius = 5
        progressBar.subviews[1].clipsToBounds = true

func startTimer() {

    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)

}

@objc func timerUpdate() {

    if timeRemaining <= 0 {
        progressBar.setProgress(Float(0), animated: false)
        bonusTimerLabel.text = "0"
        bonusTimerLabel.textColor = UIColor(red: 186/255, green: 16/255, blue: 16/255, alpha: 1)

    } else {
        progressBar.setProgress(Float(timeRemaining)/Float(10), animated: false)
        timeRemaining -= 1
        bonusTimerLabel.text = "\(timeRemaining)"
    }

Upvotes: 0

Views: 2027

Answers (2)

emrepun
emrepun

Reputation: 2666

Firing a function with timer every millisecond is not advisable, reference: https://stackoverflow.com/a/30983444/8447312

So you can fire timer func every 50 millisecond to be safe and update your progress bar. That shouldn't be too observable though.

Also make sure timeRemaining is a Double, and then just try:

func startTimer() {

    timer = Timer.scheduledTimer(timeInterval: 0.050, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)

}

@objc func timerUpdate() {

    if timeRemaining <= 0 {
        progressBar.setProgress(Float(0), animated: false)
        bonusTimerLabel.text = "0"
        bonusTimerLabel.textColor = UIColor(red: 186/255, green: 16/255, blue: 16/255, alpha: 1)

    } else {
        progressBar.setProgress(Float(timeRemaining)/Float(20), animated: false)
        timeRemaining -= 0.050
        bonusTimerLabel.text = "\(Int(timeRemaining))"
    }

Upvotes: 0

jMelvins
jMelvins

Reputation: 194

1 millisecond is 0.001 second. So change timerInterval property in timer to 0.001:

timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)

Upvotes: 0

Related Questions