3

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.

1 Answer 1

2

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

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Is there way to say timer.invalidate() when they press the button?
@josh What do you mean? You can directly call this method in the button click function to stop the timer
Can you explain how you can call this in button click function? I need to stop the timer if they click they go to the next question.
@josh Undated my answer with timer stopped in button click action
Ok Got it! Let me try that. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.