18

I am trying to create a "stop watch" type functionality. I have one label (to display the elapsed time) and two buttons (start and stop the timer). The start and stop buttons call the startTimer and stopTimer functions respectively. Every second the timer fires and calls the increaseTimerCount function. I also have an ivar timerCount which holds on to the elapsed time in seconds.

- (void)increaseTimerCount
{
    timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount++];
}

- (IBAction)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES];

}

- (IBAction)stopTimer
{
    [timer invalidate];
    [timer release];
}

The problem is that there seems to be a delay when the start button is pressed (which I am assuming is due to reinitializing the timer each time startTimer is called). Is there any way to just pause and resume the timer without invalidating it and recreating it? or a better/alternate way of doing this?

Thanks.

v0idless
  • 948
  • 2
  • 11
  • 24

2 Answers2

11

A bit dated but if someone is still interested...

don't "stop" the timer, but stop incrementing during pause, e.g.

- (void)increaseTimerCount
{
   if (!self.paused){
      timerCount++
   }

   timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount];
}
Vlad Z
  • 383
  • 2
  • 12
9

You can't pause the timer without using invalidate. What you can do is add

[timer fire];

after you create the timer in startTimer.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105