我有3个不同的定时器,我想每0.3秒发射一次,但我希望这3个定时器是交错的,这样它们就不会同时发射。例如,nstimer1在0.1处激发,然后在0.4处激发,nstimer2在0.2处激发,然后在0.5处激发,nstimer3在0.3处激发,然后在0.6处激发,如此类推。
下面是我目前正在使用的,我不确定他们是否真的同时被解雇了,我只是假设。任何建议都将不胜感激。

var timer1 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment1"), userInfo: nil, repeats: true)
var timer2 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment2"), userInfo: nil, repeats: true)
var timer3 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment3"), userInfo: nil, repeats: true)

最佳答案

你可以用积木来完成。

-(void)didMoveToView:(SKView *)view {

    SKAction *wait0 = [SKAction waitForDuration:0.1];
    SKAction *block0 = [SKAction runBlock:^{
        // run first timer code
    }];
    [self runAction:[SKAction sequence:@[wait0, block0]]];

    SKAction *wait1 = [SKAction waitForDuration:0.2];
    SKAction *block1 = [SKAction runBlock:^{
        // run second timer code
    }];
    [self runAction:[SKAction sequence:@[wait1, block1]]];

    SKAction *wait2 = [SKAction waitForDuration:0.3];
    SKAction *block2 = [SKAction runBlock:^{
        // run third timer code
    }];
    [self runAction:[SKAction sequence:@[wait2, block2]]];

}

如果您希望使用Dispatch,请尝试以下代码…
为计时器创建属性:
@property (nonatomic, strong) dispatch_source_t myTimer;

接下来,创建计时器:
// Get the queue to run the blocks on
dispatch_queue_t queue = dispatch_get_main_queue();

// Create a dispatch source, and make it into a timer that goes off every second
self.myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.myTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0);

// When the timer goes off, run your code
dispatch_source_set_event_handler(self.myTimer, ^{
    //code...
});

// Dispatch sources start out paused, so start the timer by resuming it
dispatch_resume(self.myTimer);

// To cancel the timer, just set the timer variable to nil:
self.myTimer = nil;

关于swift - 交错NSTimer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31006331/

10-14 21:25