简体   繁体   English

如何在快速while循环中添加DispatchQueue延迟?

[英]How to add DispatchQueue delay in swift while loop?

I'm trying to create a delay inside a while loop. 我正在尝试在while循环中创建延迟。 I'm fairly new to this and it's currently just not working. 我对此很陌生,目前无法正常工作。 It never fires even once with the dispatch delay, but if I remove the delay it fires repeatedly. 即使有调度延迟,它也永远不会触发,但是如果我删除延迟,它将反复触发。

Basically what I'm doing is checking if the velocity of nodes in a SKScene is still moving, if they're still moving, don't end the game. 基本上我正在做的是检查SKScene中节点的速度是否仍在移动,如果它们仍在移动,则不要结束游戏。 But once they've slowed down, end the game. 但是一旦他们放慢速度,就结束游戏。

func RemainingNodeCheck (complete:() -> Void) {

    CountVelocites()

    if (IdleVelocity.max()!.isLess(than: 1.0)) {
        complete()
    } else {

    print("Velocity too high, begin wait...")

      while !(IdleVelocity.max()?.isLess(than: 1.0))! {

                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
                    print("Second passed")
                    self.CountVelocites()
                }

            if (IdleVelocity.max()!.isLess(than: 1.0)) {
                break
            }
        }

        print("Velocity Calmed down")
        complete()
    }

}

I believe this might be something to do with threads? 我相信这可能与线程有关? Or it's actually just telling the delay to begin waiting for one second so many times that it never gets to call? 还是实际上只是在告诉延迟开始等待一秒钟的次数如此之多,以至于无法打电话?

UPDATE: I would use a timer, but the RemaingNodeCheck is being called from another part and it's waiting for RemainingNodeCheck to send back complete() 更新:我将使用一个计时器,但是RemaingNodeCheck是从另一部分调用的,它正在等待RemainingNodeCheck发送回complete()

You never want to "wait". 您永远不想“等待”。 But you can set up a repeating timer that checks for some condition, and if so, calls the complete closure (invalidating the timer, if you want). 但是,您可以设置一个重复计时器以检查某些条件,如果是,则调用complete关闭(如果需要,可以使计时器无效)。 Eg 例如

class ViewController: UIViewController {

    var idleVelocity: ...

    weak var timer: Timer?

    deinit {
        timer?.invalidate()
    }

    func startCheckingVelocity(complete: @escaping () -> Void) {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            guard let self = self, let maxVelocity = self.idleVelocity.max() else { return }

            if maxVelocity < 1 {
                timer.invalidate()
                complete()
                return
            }

            print("velocity too high...")
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM