简体   繁体   中英

How to add DispatchQueue delay in swift while loop?

I'm trying to create a delay inside a while loop. 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. 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()

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). 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...")
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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