Reputation: 3247
I have a NSTimer object as below :
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
I want to put timeout to my timer. Maybe you know postdelayed method in android. I want to same thing's swift version. How can I do this ?
Upvotes: 0
Views: 2536
Reputation: 8391
NSTimer
is not suited for variable interval times. You set it up with one specified delay time and you can't change that. A more elegant solution than stopping and starting an NSTimer
every time is to use dispatch_after
.
Borrowing from Matt's answer :
// this makes a playground work with GCD
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
struct DispatchUtils {
static func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
class Alpha {
// some delay time
var currentDelay : NSTimeInterval = 2
// a delayed function
func delayThis() {
// use this instead of NSTimer
DispatchUtils.delay(currentDelay) {
print(NSDate())
// do stuffs
// change delay for the next pass
self.currentDelay += 1
// call function again
self.delayThis()
}
}
}
let a = Alpha()
a.delayThis()
Try it in a playground. It will apply a different delay to each pass of the function.
Upvotes: 6