How to trigger NSTimer right away? How to trigger NSTimer right away? ios ios

How to trigger NSTimer right away?


NSTimer's -fire, [timer fire]; is what you're looking for.

That will fire/immediately call the timer dismissing the time delay.


You can't schedule the timer and fire the event immediately all in the same line of code. So you have to do it in 2 lines of code.

First, schedule the timer, then immediately call 'fire' on your timer:

timer = [NSTimer scheduledTimerWithTimeInterval: 5                                      target: self                                    selector: @selector(updatestuff:)                                          userInfo: nil                                     repeats: YES];[timer fire];

When fire is called, the time interval that your timer waits to fire will reset because it just ran, and then will continue to run thereafter at the designated interval--in this case, every 5 seconds.


In Swift:

timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(foo), userInfo: nil, repeats: true)timer.fire()