0

Sorry if this is a newbie question, I am very new to iOS & Swift. I have a timer, I know I could use 'CADisplayLink', but if I use it, my milliseconds in my timer will jump like 1, 3, 7... 67, 71... I don't need this, I need 1, 2, 3, 4, 5 ... 54, 55, 56 , 57... In iPhone 7, iPhone 7 Plus, iPhone 5 function pretty good, but in iPhone SE, iPad Retina, iPad Pro, iPad Air the timer is too much slow, so basically the timer is skewed.

The timer doesn't run as good as the one in the default timer app (FPS issue?)

I need milliseconds make each step:

func updateStopwatch() {
    milliseconds += 1
    print(milliseconds)
    if milliseconds == 100 {
        milliseconds = 0
        seconds += 1
    }
    let millisecondsString = milliseconds > 9 ?"\(milliseconds)" : "0\(milliseconds)"
    let secondsString = seconds > 9 ?"\(seconds)" : "\(seconds)"
    stopWatchString = "\(secondsString).\(millisecondsString)"
    labelTimer.text = stopWatchString
}

@IBAction func startStopButtonTapped(_ sender: Any) {
    if isTimerRunning {
        isTimerRunning = !isTimerRunning
        timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(updateStopwatch), userInfo: nil, repeats: true)
    }else{
        isTimerRunning = !isTimerRunning
        timer.invalidate()
    }
}
Edoardo
  • 657
  • 7
  • 24
  • 1
    Two comments. 1) The display doesn't update that fast anyway, so don't worry about displaying that many digits when the timer is running. 2) Timer isn't that accurate. It isn't guaranteed to be called on the interval you are asking for, especially with a value as small as `0.001`. You should instead take a clock reading when you start the timer and then at each *tick* and compute the difference at that time and update the display. – vacawama Jul 29 '17 at 21:46
  • Good info here: https://stackoverflow.com/q/31375361/1630618 – vacawama Jul 29 '17 at 21:56

1 Answers1

1

There's no reason to update screen each millisecond. If you really need timer to fire so fast you need some optimisation here. At first try update labelTimer.text (and calculate string for that) each 40 or even 100 milliseconds, there's no difference in user experience.

P.S.: there's typo in forth line: you need thousand, not hundred.