Timer decrement gets varied for each page load

前端 未结 2 1643
情深已故
情深已故 2021-01-16 17:55

I have a timer for my project, each time it decrements by 1 second. But if the counter starts working for the second time it gets decremented by 2 seconds and for the third

2条回答
  •  情话喂你
    2021-01-16 18:44

    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;
        }
    }
    

提交回复
热议问题