Search code examples
swiftnstimer

NSTimer.scheduledTimerWithTimeInterval() with variable delay


I have a function that need to be called every x second. At the begining x = 5 but everytime it calls this function x need to decrement by a certain number. I know how to do it if x is constant:

override func didMoveToView(view: SKView) {
    NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("function"), userInfo: nil, repeats: true)
}

func function(){
    println("TEST")
}

How could I decrement the delay between each function calls each time it gets called?


Solution

  • I would change your code like this:

    var timeDuration: NSTimeInterval = 5
    
    override func didMoveToView(view: SKView) {
       NSTimer.scheduledTimerWithTimeInterval(timeDuration, target: self, selector: Selector("function"), userInfo: nil, repeats: false)
    }
    
    func function(){
        println("TEST")
        timeDuration -= 1
        if timeDuration > 0{
            NSTimer.scheduledTimerWithTimeInterval(timeDuration, target: self, selector: Selector("function"), userInfo: nil, repeats: false)
        }
    }
    

    This should work, have not tested it.