Search code examples
iphonetimernstimeinterval

Increase timeInterval of a Timer


Possible Duplicate:
Change the time interval of a Timer

So I have a timer:

timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];

And I would like that the timer decrease every ten seconds, that scheduledTimerWithTimeInterval goes to 1.5 after ten seconds then to 1.0 after 10 seconds... Is it possible to do this, and if it is possible, how can I do it?


Solution

  • You don't have to use several timers, all you have to do is add a variable to use for the time interval, then create a method that invalidates the timer, changes the variable and starts the timer again. For instance you could make a method that starts the timer.

    int iTimerInterval = 2;
    
    -(void) mTimerStart {
        timer = [NSTimer scheduledTimerWithTimeInterval:iTimerInterval target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];
    }
    
    -(void) mTimerStop {
        [timer invalidate];
    
        iTimerInterval = iTimerInterval + 5;
    
        [self mTimerStart];
    }
    

    This would be the simple way to decrease the timer interval and keep the timer going, but I would personally prefer using the one below, because it makes sure that the timer has only ran once, that way it will not duplicate the instance, forcing your app to become glitchy and it also makes things easier for you.

    int iTimerInterval = 2;
    int iTimerIncrementAmount = 5;
    int iTimerCount;
    int iTimerChange = 10; //Variable to change the timer after the amount of time
    bool bTimerRunning = FALSE;
    
    -(void) mTimerToggle:(BOOL)bTimerShouldRun {
        if (bTimerShouldRun == TRUE) {
            if (bTimerRunning == FALSE) {
                timer = [NSTimer scheduledTimerWithTimeInterval:iTimerInterval target:self selector:@selector(mCreateNewImage) userInfo:nil repeats:YES];
                bTimerRunning = TRUE;
            }
        } else if (bTimerShouldRun == FALSE) {
            if (bTimerRunning == TRUE) {
                [timer invalidate];
                bTimerRunning = FALSE;
            }
        }
    }
    
    -(void) mCreateNewImage {
        //Your Code Goes Here
    
        if (iTimerCount % iTimerChange == 0) { //10 Second Increments
            iTimerInterval = iTimerInterval + iTimerIncrementAmount; //Increments by Variable's amount
    
            [self mTimerToggle:FALSE]; //Stops Timer
            [self mTimerToggle:TRUE]; //Starts Timer
        }
    
        iTimerCount ++;
    }
    
    -(void) mYourMethodThatStartsTimer {
        [self mTimerToggle:TRUE];
    }
    

    I didn't finish all of the coding, but this is most of what you will need. Just change a few things and you'll be good to go!