how to pause and resume NSTimer in iphone

Hardik Patel picture Hardik Patel · Nov 10, 2010 · Viewed 16.9k times · Source

hello I am developing small gameApp. I need to pause the timer,when user goes to another view [say settings view]. when user comes back to that view , I need to resume the timer.

can anybody solve this issue ...

Thanks in Advance...

Answer

tybro0103 picture tybro0103 · Aug 19, 2012

NSTimer does not give you the ability to pause it. However, with a few simple variables, you can create the effect yourself:

NSTimer *timer;
double timerInterval = 10.0;
double timerElapsed = 0.0;
NSDate *timerStarted;

-(void) startTimer {
  timer = [NSTimer scheduledTimerWithTimeInterval:(timerInterval - timerElapsed) target:self selector:@selector(fired) userInfo:nil repeats:NO];
  timerStarted = [NSDate date];
}

-(void) fired {
  [timer invalidate];
  timer = nil;
  timerElapsed = 0.0;
  [self startTimer];
  // react to timer event here
}

-(void) pauseTimer {
  [timer invalidate];
  timer = nil;
  timerElapsed = [[NSDate date] timeIntervalSinceDate:timerStarted];
}

This has been working out quite well for me.