Question

How can I programmatically pause an NSTimer?

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 I'd like to "pause" i.e. something like this:

[myNSTimer pause];

I'm using this syntax because I've been doing things like:

[myNSTimer invalidate];

when I want it to stop.

How can I programmatically pause the NSTimer?

 45  44986  45
1 Jan 1970

Solution

 36

Just thought of updating minor fixes to kapesoftware's answer:

NSDate *pauseStart, *previousFireDate;

-(void) pauseTimer:(NSTimer *)timer { 

    pauseStart = [[NSDate dateWithTimeIntervalSinceNow:0] retain];

    previousFireDate = [[timer fireDate] retain];

    [timer setFireDate:[NSDate distantFuture]];
}

-(void) resumeTimer:(NSTimer *)timer {

    float pauseTime = -1*[pauseStart timeIntervalSinceNow];

    [timer setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];

    [pauseStart release];

    [previousFireDate release];
}
2011-07-20

Solution

 22

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. "

2008-12-07