Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an iOS Timer

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.

like image 914
v0idless Avatar asked Jul 15 '11 18:07

v0idless


People also ask

How do I set a custom timer on my iPhone?

Invoke Control Center by swiping down diagonally from the top-right of the screen. (If your ‌iPhone‌ has a Home button, swipe up from the bottom of the screen.) Long press on the Timer button. Swipe up on the slider to set the timer duration, then tap Start.

Can you preset iPhone timer?

In the Clock app , you can use the timer to count down from a specified time. You can also use the stopwatch to measure the duration of an event. Siri: Say something like: “Set the timer for 3 minutes” or “Stop the timer.” Learn how to use Siri.

How do you make a multiple timer with Apple?

To do so, swipe right on the lock screen, then tap "Set Multiple Timers" in the Shortcuts widget (you may have to tap "Show More" to see it, depending on how many shortcuts you have).


2 Answers

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];
}
like image 103
Vlad Z Avatar answered Oct 03 '22 08:10

Vlad Z


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

[timer fire];

after you create the timer in startTimer.

like image 44
Deepak Danduprolu Avatar answered Oct 03 '22 10:10

Deepak Danduprolu