Swift timer not following correct interval

350 views Asked by At

I am trying to create a quiz app which has a timer for each question when the timer expires (i.e. 10 seconds and I want Timmer to have an interval of 1 sec) it resets it self and next question is fetched and Timmer again restart from 10... But my issue is the timer doesn't follow a fixed interval when first question is loaded it shows interval of 2 ... i.e. 10,8,6 .. and then for second question it makes jump for 3 secs interval and similarly the interval increases.

var countTime = 10.0
func handleNextQuestion() throws {
            nextQuestion()
            if questionCounter == allQuestions.list.count-1{
                finishButton.isHidden = false
                nextButton.isHidden = true
                //scoreLbl.text = "\(score)"
            }
        }
        
        func nextQuestion(){
            showResultView(isCorrect: (question?.isAnswerCorrect)!)
            questionCounter = questionCounter + 1
            question = fetchQuestion()
            setQuizView(question: question!)
            
            
        }
        
        @objc func update() {
            if(countTime > 0) {
                countTime = countTime - 1
                self.countDownLabel.text = String(countTime)
            }else{
                timer.invalidate()
                countTime = 10.0
                do{
    
                    try handleNextQuestion()
    
                }
                catch{
                       moveToResultView()
                }
                
            }
        }
     
        
       
        func startTimer() {
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
        }
        func setQuizView(question:Question)  {
            self.countDownLabel.text = "10"
          startTimer()
            startTimer()
            questionLabel.text =  question.questionText
            ansLbl1.text =  question.answer1
            ansLbl2.text =  question.answer2
            ansLbl3.text =  question.answer3
            ansLbl4.text =  question.answer4
            
            if question.selectedAnswer == Constants.DEFAULT_ANSWER {
                for checkBoxItem in checkBoxlist{
                    checkBoxItem.isChecked = false
                }
                
            }
            
        }
        
1

There are 1 answers

0
Tim On

func setQuizView(question:Question)

calls startTimer() twice. I think that explains the behaviour. On each new question the timer is started twice but only invalidated once so the seconds jump by an extra one exach question.

just delete one of the calls to startTimer()