Call a function once per second for 10 seconds

放肆的年华 提交于 2019-12-12 01:56:23

问题


I need to know how you can perform an operation for total time, I'll explain, I need to repeat my call to a function for 10 seconds and then just every 1, I tried using a timer, but I understand what's called function EVERY 10sec and not FOR 10 sec.

Does anyone have any ideas?

thanks


回答1:


I'm guessing you mean that you want to call a function once per second, and stop calling it after ten seconds. And I suspect that you will want to be able to change the interval (once per second) and the duration (10 seconds).

@implementation Example
{
    NSTimer *_timer;
    NSTimeInterval _stopTime;
}

- (void)setTimerWithInterval:(NSTimeInterval)interval duration:(NSTimeInterval)duration
{
    [_timer invalidate];
    _timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerDidFire) userInfo:nil repeats:YES];
    _stopTime = [NSDate timeIntervalSinceReferenceDate] + duration;
}

- (void)timerDidFire
{
    if ([NSDate timeIntervalSinceReferenceDate] >= _stopTime) {
        [_timer invalidate];
        return;
    }
    NSLog(@"hello from the timer!");
}

- (void)dealloc
{
    [_timer invalidate];
    [super dealloc];  // delete this line if using ARC
}

@end


来源:https://stackoverflow.com/questions/8164095/call-a-function-once-per-second-for-10-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!