Reputation: 49
I want my NSTimer
to speed up each time it's run:
-(void)runtimer {
int delay = delay - 1;
[NSTimer scheduledTimerWithTimeInterval:(delay)
target:self
selector:@selector(timerTriggered:)
userInfo:nil
repeats:YES];
}
But this doesn't work. How can I make the delay keep getting smaller and smaller?
Upvotes: 0
Views: 1057
Reputation: 5699
I needed this myself and wrote a component CPAccelerationTimer (Github):
[[CPAccelerationTimer accelerationTimerWithTicks:20
totalDuration:10.0
controlPoint1:CGPointMake(0.5, 0.0) // ease in
controlPoint2:CGPointMake(1.0, 1.0)
atEachTickDo:^(NSUInteger tickIndex) {
[self timerTriggered:nil];
} completion:^{
[self timerTriggered:nil];
}]
run];
This calls -timerTriggered:
20 times, spread out over 10 seconds, with ever-decreasing delays (as specified by the given Bézier curve).
Upvotes: 3
Reputation: 64002
Every time this method is run, you make a new variable called delay
, then try to set it to itself minus 1. This is Undefined Behavior (the variable was not initialized to anything), and is likely to result in a garbage value for delay
.*
You need to store the delay in an instance variable.
- (void) runTimer {
// You are declaring a new int called |delay| here.
int delay = delay - 1;
// This is not the same |delay| that you have declared in your header.
// To access that variable, use:
delay = delay - 1;
*A sinus infestation by evil-aligned supernatural beings is also a possibility.
Upvotes: 1
Reputation: 19884
You have to declare the delay somewhere, like in the class interface or as a static variable.
Also, create a new timer every time, instead of having it repeat.
int delay = INITIAL_DELAY;
-(void)runtimer{
[NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(delay--) target:self selector:@selector(runTimer:) userInfo:nil repeats:NO];
}
Upvotes: 0
Reputation: 16827
You cannot change the fire interval of the timer once you have created it. If you want a different interval you must invalidate the previous timer (hence you should keep a reference to it), and create a new timer with a different interval.
Upvotes: 0