barola_mes
barola_mes

Reputation: 1640

How to wait until timer stops

I have a reusable function countDown(seconds: Int) that contains Timer object. Function takeRest() calls countDown(seconds: Int) function and after calling immediately prints: "test text". What I'd like to do is to wait with executing print function until timer inside countDown(seconds: Int) function stop executing and keep countDown() function reusable. Any suggestions?

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()
            }
        }
    }
}

Upvotes: 1

Views: 364

Answers (1)

dip
dip

Reputation: 3598

You can use closure on countdown function, Please refer following code for reference.

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

Upvotes: 1

Related Questions