mkz
mkz

Reputation: 2302

create nstimer for direct number of seconds

I need to call a function every 0.1s during certain number of seconds.

I've tried to achieve this by creating two NSTimers:

cameraLocalTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "performStep", userInfo: nil, repeats: true)
cameraGlobalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "captureShouldEnd", userInfo: nil, repeats: false)

Then I've implemented their functions like this:

var stepCounter = 0
func performStep() {
    stepCounter++
    print(stepCounter)
}

func captureShouldEnd() {
    cameraGlobalTimer.invalidate()
    cameraLocalTimer.invalidate()
    stepCounter = 0
}

But when I run my application I see in log that cameraLocalTimer is called 47 times, not 50.

Can someone help me with my issue or suggest a better way to do this?

Upvotes: 0

Views: 53

Answers (1)

Danny Bravo
Danny Bravo

Reputation: 4658

If you want to achieve this level of high precision NSTimer will not suffice. According to the documentation on NSTimer:

A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed. Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds.

Which means that you might skip a beat. For higher precision, I suggest you look into CADisplayLink, it's a lower level feature that taps into the screen refresh rate and provides you with a timestamp that you can use to run your calculations. Having said that, the fidelity will always depend on your screen refresh rate.

Upvotes: 1

Related Questions