Nstimer count wrong

2019-08-20 11:29发布

I have a problem with NSTimer. I start and repeat it every 100ms and I have a counter to check if i runed 10s. The problem is it stoped in near 1 minute, not in 10s. Here is my code

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

-(void)checkTimer
{

    timerCount += 1;

        if(timerCount == 1)
        {
                NSLog(@"start");
        }

        if(timerCount == 103)
        {
            NSLog(@"i got it");
        }
}

here is the log:

2012-11-19 08:57:42.063 Karagram[11708:540b] start
[Switching to process 8707 thread 0x2203]
2012-11-19 08:58:39.514 Karagram[11708:540b] i got it

I don't understand why it wrong. Somebody can tell me why? Thanks.

1条回答
太酷不给撩
2楼-- · 2019-08-20 11:57

NSTimers aren't guaranteed to be accurate to within more than 100 ms or so. The NSTimer documentation says:

A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed. Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs during a long callout or while the run loop is in a mode that is not monitoring the timer, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.

By having it fire every 100ms you're compounding the error, because if it's off 50 ms every 100ms, by the time 10s has passed it could be quite far from what you expect.

If you're wanting to take some action after 10s, why not just set the timer to fire after 10s?

NSLog( @"start" );
timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(checkTimer) userInfo:nil repeats:YES];

-(void)checkTimer
{
    NSLog(@"i got it");
}

Also, are you doing your streaming on the main thread? NSTimers work on the main runloop, so if you're blocking the main thread, timers aren't going to fire until it's unblocked.

查看更多
登录 后发表回答