user4790024
user4790024

Reputation:

Delay timer after first fire

I have a timer in my application that triggers a certain event:

myTimer =  NSTimer.scheduledTimerWithTimeInterval(10, target: self,
    selector: "searchForDrivers:", userInfo:nil, repeats: true)

The first time the timer is triggered, it has a delay of 10 ms. I don’t want the delay on the first timer trigger, but I'd like the second trigger to be delayed by 10 ms. How can I achieve this?

Upvotes: 2

Views: 1721

Answers (2)

ndmeiri
ndmeiri

Reputation: 5039

First schedule the timer as you've done.

timer =  NSTimer.scheduledTimerWithTimeInterval(
    10.0, target: self,
    selector: "searchForDrivers:",
    userInfo: nil,
    repeats: true
)

Then, immediately afterwards, fire timer.

timer.fire()

According to the documentation,

You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

See the NSTimer Class Reference for more information.

Upvotes: 4

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

One more way to do that is you can use two timers for that like:

var myTimer = NSTimer()
var secondTimer = NSTimer()

After that you can set two timers this way:

myTimer =  NSTimer.scheduledTimerWithTimeInterval(0, target: self,
    selector: "searchForTRuckDrivers", userInfo:nil, repeats: false)
secondTimer =  NSTimer.scheduledTimerWithTimeInterval(10, target: self,
    selector: "searchForTRuckDrivers", userInfo:nil, repeats: true)

You can set first timer with delay 0 which will not repeat again while set another timer with delay 10 and it will repeat again and again.

After that in method you can invalidate first timer this way:

func searchForTRuckDrivers() {        
    if myTimer.valid {
        myTimer.invalidate()
    }
}

This will remove first timer but second timer will call this method with delay.

Hope it will help.

Upvotes: 0

Related Questions