错开 NSTimer

Stagger NSTimer

我有 3 个不同的 NSTimer,我想每 0.3 秒触发一次,但我希望 3 个 NSTimer 交错排列,这样它们就不会同时触发。例如,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]]];

}

如果您想使用分派,试试这个代码...

为您的计时器创建一个 属性:

@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;

我建议您在 Sprite Kit 游戏中使用一两个 SKAction 而不是 NSTimer,因为当您 pause/resume SKView and/or SKScene。以下是如何使用 SKActions 错开事件的示例:

override func didMoveToView(view:SKView) {

    let wait = SKAction.waitForDuration(0.1)
    let block1 = SKAction.runBlock({
        updateSegment1()
    })
    let block2 = SKAction.runBlock({
        updateSegment2()
    })
    let block3 = SKAction.runBlock({
        updateSegment3()
    })
    let sequence = SKAction.sequence([wait,block1,wait,block2,wait,block3])
    self.runAction(SKAction.repeatActionForever(sequence), withKey:"timer")

    // Use the following to terminate the timer
    //self.removeActionForKey("timer")
}