Search code examples
swiftloopsuser-interfacedelaydelayed-job

Wait itself within endless loop, but user can cancel every time


In Swift 3 I have a loop which can be canceled by user pressing a button. Within the loop some checks are made. After the check, the task can sleep for a minute. But when calling the task with

let delayQueue = DispatchQueue(label: "com.myApp.queue3", qos: .utility)
let additionalTime: DispatchTimeInterval = .seconds(3)

repeat {
    delayQueue.asyncAfter(deadline: .now() + additionalTime) { self.update() }
} while !self.stop

the loop itself needs to run all the time waiting for the user "stop", indicates, that user clicked on stop button. Is that waste of CPU power? How could I avoid this loop to be done all the time?


Solution

  • You should use Timer instead.

    var timer: Timer?
    let timeInterval: TimeInterval = 3
    
    func didPressCancelButton() {
        timer?.invalidate()
    }
    
    func beginUpdates() {
        timer = Timer.scheduledTimer(
            timeInterval: timeInterval,
            target: self, 
            selector: #selector(self.update),
            userInfo: nil, 
            repeats: true
        );
    }
    
    func update() {
        print("Updated")
    }