Roi Mulia
Roi Mulia

Reputation: 5896

Swift- Get how much sec/millisecond passes since timer started

trying to figure out how to get the time passed since timer started. this is what i did : Feel free to suggest other ways to get the time passed since the page loaded

Declared timer :

 var runner = NSTimer()
 runner = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("time"),      userInfo: nil, repeats: true)

Than tried this in the function,returns the interval i set(obviously)

  func time() {

        println(self.runner.timeInterval)
    }

anyway if getting how much time passes since it started? (it's in the didload section so it like saying how much time passes since the page loaded). thanks ! :D

Upvotes: 3

Views: 9746

Answers (1)

Steve Rosenberg
Steve Rosenberg

Reputation: 19524

Put this in a playground. I added the loop just to create a time lag. Time in seconds down to fractions of a second.

var startTime = NSDate.timeIntervalSinceReferenceDate()
var currentTime: NSTimeInterval = 0

for var i = 0; i < 10000; i++ {
    if i == 99 {
        currentTime = NSDate.timeIntervalSinceReferenceDate()
        println(i)
    }

}
var elapsedTime = currentTime - startTime
println(Double(elapsedTime))

From: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/instp/NSDate/timeIntervalSinceReferenceDate

timeIntervalSinceReferenceDate

Returns the interval between the date object and January 1, 2001, at 12:00 a.m. GMT. (in seconds)

The method is establishing a startTime whenever you want to start. It is a time in seconds since the reference. Later we set the currentTime to be equal to the new time since the reference time. Subtracting one from the other gives elapsed time. There is several decimal place precision.

Upvotes: 4

Related Questions