Timer decrement gets varied for each page load

岁酱吖の 提交于 2019-12-01 14:37:59

From what you've posted, you're creating multiple timers and not stopping any of them. So after 3 times, you have 3 timers firing each second.

At a minimum, when the timer hits zero you want to invalidate it:

[theTimer invalidate]

But you may also want to consider holding onto the timer you create (in a @property) so that you can invalidate and release it if the user leaves this view some other way before your counter actually goes to zero.

Hope that helps.

EDIT
(Just as I posted this I notice that you have know accepted the above answer and seemed to have removed your 'its not working' comment for the answer from @Firoze Lafeer. But I will leave this here any way.)

Running the code below as a test I do not get your issue. And even when I did not invalidate I just got multiple outputs in the log.

Instead of seeing what is going on by looking at what the textfield in the app is doing. Try and use logging as I have below to see if that gives you a better idea of what is happening.

-(IBAction)runTimer:(id)sender { // attached to a button
    [self invalidateTimer];
    count=15; //timer set as 15 seconds 
    //for decrementing timer
    countimer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                target:self
                                              selector:@selector(updateCounter:) 
                                              userInfo:nil
                                               repeats:YES];
}

-(void)updateCounter:(NSTimer *)theTimer { 
    count -= 1; 
    NSLog (@"count =@%d", count);          
    if(count==0) // alert for time expiry 
    { 
        [self invalidateTimer];
    }
}

-(void)invalidateTimer {
    if ([countimer isValid]) {
        [countimer invalidate];
        NSLog(@"countimer invalidated ");
        countimer = nil;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!