How to create Countdown with 10th of a second?

mikemike picture mikemike · Apr 8, 2011 · Viewed 7.2k times · Source

HI I have already created a countdown in second, lets say 10 second, but I want to make it more precise

to 10.0 and display it on a label, how do it do that? Thanks in advance

This is what I have now for the "second" countdown

my NSTimer

counterSecond = 10
NSTimer timer1 = [NSTimer scheduledTimerWithTimeInterval : 1
    Target:self selector:@selector (countLabel) userInfo:nil repeats:YES];



-(void)countLabel:
counterSecond --;

self.timerLabel.text = [NSString stringWithFormat @"%d", counterSecond];

Answer

Black Frog picture Black Frog · Apr 9, 2011

I would use a start date/time to keep track of the countdown. Because iOS can delay firing the timer for other tasks.

- (void)countdownUpdateMethod:(NSTimer*)theTimer {
    // code is written so one can see everything that is happening
    // I am sure, some people would combine a few of the lines together
    NSDate *currentDate = [NSDate date];
    NSTimeInterval elaspedTime = [currentDate timeIntervalSinceDate:startTime];

    NSTimeInterval difference = countdownSeconds - elaspedTime;
    if (difference <= 0) {
        [theTimer invalidate];  // kill the timer
        [startTime release];    // release the start time we don't need it anymore
        difference = 0;         // set to zero just in case iOS fired the timer late
        // play a sound asynchronously if you like
    }

    // update the label with the remainding seconds
    countdownLabel.text = [NSString stringWithFormat:@"Seconds: %.1f", difference];
}

- (IBAction)startCountdown {
    countdownSeconds = 10;  // Set this to whatever you want
    startTime = [[NSDate date] retain];

    // update the label
    countdownLabel.text = [NSString stringWithFormat:@"Seconds: %.1f", countdownSeconds];

    // create the timer, hold a reference to the timer if we want to cancel ahead of countdown
    // in this example, I don't need it
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector     (countdownUpdateMethod:) userInfo:nil repeats:YES];

    // couple of points:
    // 1. we have to invalidate the timer if we the view unloads before the end
    // 2. also release the NSDate if don't reach the end
}