Reputation: 145
Overview: I am trying to create quiz game where someone has to answer questions in a certain amount of time. They have 10 seconds to solve each question or it will move to the next controller. The problem is that whenever I click next question before the full time is up it keeps counting down to 10. What should happen is it should stop counting time for that question.
So far I have implemented the following code to try to make this work. var time = 0
and first created a global variable called time. Then I created timer code as following, var count = 10
@IBOutlet var countDownLabel: UILabel!
Then I create a label that will tick down every second until it reaches 0. Code as follows:
if(count > 0) {
countDownLabel.text = String(count)
count -= 1
time += 1
}
print (time)
if (count <= 0 ) {
count = 10
self.performSegue(withIdentifier:"NextQuestion1", sender: nil)
}
Summary: Everytime count goes down time should go up. Then at the end it will display the time they. I would gladly appreciate some help on this problem.
Upvotes: 3
Views: 79
Reputation: 25261
When you click on the next button, you need to invalidate the timer so that it will stop counting.
Say you created your timer in this way
let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(YourSegueFunction), userInfo: nil, repeats: false)
Then when you click on the next button, use the following line of code to stop the timer
timer.invalidate()
Here is the demo
Upvotes: 2