具有可变延迟的NSTimer.scheduledTimerWithTimeInterval()

时间:2015-03-16 23:11:45

标签: swift nstimer

我有一个需要每隔x秒调用一次的函数。在开始时x = 5,但每次调用此函数x都需要递减一定数量。如果x是常数,我知道怎么做:

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

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

每次调用每个函数调用时,我怎样才能减少延迟?

1 个答案:

答案 0 :(得分:2)

我会改变你的代码:

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)
    }
}

这应该有效,尚未测试过。