Search code examples
iphonenstimerfunction-callsnstimeinterval

iPhone - NSTimer and only calling a function a minimum of n seconds after function last run


just a quick question. I have a function called multiple times with a 5 second period. Is there way to incorporate an NSTimer so that there is a pause between the function calls (ie so there is no way the function can be called before the timer has reached a certain limit)? Any and all suggestions are appreciated!

Alex


Solution

  • If you do not want a certain method to be invoked for a certain time period after it has been invoked, you can do this,

    - (void)methodThatDoesStuff {
        static NSDate * lastCalled = nil;
        if ( [[NSDate date] timeIntervalSinceDate:lastCalled] < 5 ) {
            NSLog(@"Call Blocked");
            return;
        }
    
        NSLog(@"Called");
    
        [lastCalled release];
        lastCalled = [[NSDate date] retain];
    }
    

    This will block all method calls for 5 seconds after the method has been run successfully.