如何等到计时器停止

How to wait until timer stops

我有一个包含 Timer 对象的可重用函数 countDown(seconds: Int)。函数 takeRest() 调用 countDown(seconds: Int) 函数,调用后立即打印:"test text"。我想做的是等待执行打印函数,直到 countDown(seconds: Int) 函数内的计时器停止执行并保持 countDown() 函数可重用。有什么建议吗?

private func takeRest(){
            countDown(seconds: 10)
            print("test text")
        }

private func countDown(seconds: Int){
        secondsToCount = seconds
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ [weak self] timer in
            if (self?.secondsToCount)! > 0{
                self?.secondsToCount -= 1
                self?.timerDisplay.text = String((self?.secondsToCount)!)
            }
            else{
                self?.timer.invalidate()
            }
        }
    }
}

您可以在倒计时功能上使用闭包,请参考以下代码。

private func takeRest(){
        countDown(seconds: 10) { 
            print("test text")
        }
    }

private func countDown(seconds: Int, then:@escaping ()->() ){
    let secondsToCount = seconds
    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ [weak self] timer in
        if (self?.secondsToCount)! > 0{
            self?.secondsToCount -= 1
            self?.timerDisplay.text = String((self?.secondsToCount)!)

            //call closure when your want to print the text.
            //then()
        }
        else{
            //call closure when your want to print the text.
            then()
            self?.timer.invalidate()
            self?.timer = nil // You need to nil the timer to ensure timer has completely stopped. 
        }
    }
}