每次运行延迟循环

时间:2015-12-05 15:09:15

标签: swift for-loop delay

我想每2秒运行 hs.robber.step() 6次。使用下面的代码,它会等待2秒,然后一次执行所有6次。

你能为我找到错误吗?

我使用了此处的代码:How to add a time delay in swift

func delay(delay:Double, closure:()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
}

func displayEscape() {
 for _ in 1...6 {

  let timeToDelay = Double(2)

  delay(timeToDelay) {
   self.hs.robber.step()
  }
 }
}

2 个答案:

答案 0 :(得分:1)

您为每次迭代设置相同的延迟。你必须每次迭代增加延迟,使它看起来像你想要的(每2秒运行6次)。类似的东西:

func delay(delay:Double, closure:()->()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
}

func displayEscape() {
    let timeToDelay: Double = 2
    var currentDelay: Double = 0
    for _ in 1...6 {
        currentDelay += timeToDelay
        delay(currentDelay) {
            self.hs.robber.step()
        }
    }
}

答案 1 :(得分:1)

dispatch_time()调用将在未来创建特定时间,而不是相对更改。将其计算放在循环中,如下所示。

func displayEscape() {
  let delay = Int64(2.0 * Double(NSEC_PER_SEC))
  for step in 1...6 {
    dispatch_after(
      dispatch_time(DISPATCH_TIME_NOW, (Int64(step) * delay)),
      dispatch_get_main_queue(),
      { self.hs.robber.step() })
  }
}