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.