每秒调用一次函数,持续 10 秒 [英] Call a function once per second for 10 seconds

查看:64
本文介绍了每秒调用一次函数,持续 10 秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何在总时间内执行操作,我会解释,我需要重复调​​用一个函数 10 秒,然后每隔 1 秒,我尝试使用计时器,但我明白什么是每 10 秒调用一次函数,而不是 10 秒.

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.

有人有什么想法吗?

谢谢

推荐答案

我猜你的意思是你想每秒调用一次函数,十秒后停止调用它.我怀疑您可能希望能够更改间隔(每秒一次)和持续时间(10 秒).

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

这篇关于每秒调用一次函数,持续 10 秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆