AleMal
AleMal

Reputation: 2077

Call a function once per second for 10 seconds

I need to know how you can perform an operation for total time, I'll explain, I need to repeat my call to a function for 10 seconds and then just every 1, I tried using a timer, but I understand what's called function EVERY 10sec and not FOR 10 sec.

Does anyone have any ideas?

thanks

Upvotes: 0

Views: 788

Answers (1)

rob mayoff
rob mayoff

Reputation: 385998

I'm guessing you mean that you want to call a function once per second, and stop calling it after ten seconds. And I suspect that you will want to be able to change the interval (once per second) and the duration (10 seconds).

@implementation Example
{
    NSTimer *_timer;
    NSTimeInterval _stopTime;
}

- (void)setTimerWithInterval:(NSTimeInterval)interval duration:(NSTimeInterval)duration
{
    [_timer invalidate];
    _timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerDidFire) userInfo:nil repeats:YES];
    _stopTime = [NSDate timeIntervalSinceReferenceDate] + duration;
}

- (void)timerDidFire
{
    if ([NSDate timeIntervalSinceReferenceDate] >= _stopTime) {
        [_timer invalidate];
        return;
    }
    NSLog(@"hello from the timer!");
}

- (void)dealloc
{
    [_timer invalidate];
    [super dealloc];  // delete this line if using ARC
}

@end

Upvotes: 1

Related Questions