Reset an NSTimer's firing time to be from now instead of the last fire

前端 未结 5 558
面向向阳花
面向向阳花 2021-01-02 13:33

I have a NSTimer that fires with an interval of 3 seconds to decrease a value. When I do an action that increases that value, I want to restart the timer to cou

5条回答
  •  执笔经年
    2021-01-02 13:41

    I've done a little testing, and it turns out that resetting the fireDate is about four times faster than invalidating and re-creating the timer. First, I create a timer which calls the method doNothing:

    if (!testTimer) {
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                          target:self
                                                        selector:@selector(doNothing:)
                                                        userInfo:nil
                                                         repeats:NO];
        testTimer   = timer;
    }
    

    Here is the test code:

    - (void) testInvalidatingTimer {
        for (int n = 0; n < 10000; n++) {
            [testTimer invalidate];
            testTimer = nil;
    
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                              target:self
                                                            selector:@selector(doNothing:)
                                                            userInfo:nil
                                                             repeats:NO];
            testTimer   = timer;
        }
    }
    
    - (void) testResettingTimer {
        for (int n = 0; n < 10000; n++) {
            if ([testTimer isValid]) {
                testTimer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3.0];
            }
        }
    }
    

    Running that on an iPad Air yields 0.198173 s for invalidatingTimer and 0.044207 s for resettingTimer. If performance is your target, I recommend to reset the fireDate. It is also quite a bit less coding effort.

提交回复
热议问题