I\'m using an NSTimer to do some rendering in an OpenGL based iPhone app. I have a modal dialog box that pops up and requests user input. While the user is providing input
From here:
http://discussions.apple.com/thread.jspa?threadID=1811475&tstart=75
"You can store the amount of time that has passed since the timer started... When the timer starts store the date in an NSDate variable. Then when the user switches... use the method timeIntervalSinceNow in the NSDate class to store how much time has passed... note that this will give a negative value for timeIntervalSinceNow. When the user returns use that value to set an appropriate timer.
I don't think there's a way to pause and restart a timer. I faced a similar situation. "
Well, I find this as the best method to implement the pausing a timer thing. Use a static variable to toggle pause and resume. In pause, invalidate the timer and set it to nil and in the resume section reset the timer using the original code by which it was started.
The following code works on the response to a pause button click.
-(IBAction)Pause:(id)sender
{
static BOOL *PauseToggle;
if(!PauseToggle)
{
[timer invalidate];
timer = nil;
PauseToggle = (BOOL *) YES;
}
else
{
timer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:@selector(HeliMove) userInfo:nil repeats:YES];
PauseToggle = (BOOL *) NO;
}
}
Here is a Simple swift pause/play timer.
https://github.com/AnthonyUccello/Swift-Pausable-Timer/blob/master/Timer.swift
In my case, I had a variable 'seconds', and another 'timerIsEnabled'. When I wanted to pause the timer, just made the timerIsEnabled as false. Since the seconds variable was only incremented if timerIsEnabled was true, I fixed my problem. Hope this helps.
The easiest way I managed to do it was like this:
-(void) timerToggle{
if (theTimer == nil) {
float theInterval = 1.0/30.0;
theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(animateBall:) userInfo:nil repeats:YES];
} else {
[theTimer invalidate];
theTimer = nil;
}
}
Old question, but I just wrote a lightweight utility class to accomplish exactly what OP is looking for.
https://github.com/codeslaw/CSPausibleTimer
Supports repeating timers as well. Hope it comes in handy!