首页 > 解决方案 > Swift 计时器未遵循正确的时间间隔

问题描述

我正在尝试创建一个测验应用程序,它在计时器到期时(即 10 秒,我希望Timmer有 1 秒的间隔)为每个问题设置一个计时器,它会自行重置并获取下一个问题并Timmer再次从 10.. . 但我的问题是,当第一个问题被加载时,计时器没有遵循固定的时间间隔,它显示的时间间隔为 2 ... 即 10,8,6 .. 然后对于第二个问题,它会跳转 3 秒的时间间隔,类似地间隔增加。

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

标签: swiftnstimerios13

解决方案


func setQuizView(question:Question)

调用startTimer()两次。我认为这解释了这种行为。在每个新问题上,计时器都会启动两次,但只会失效一次,因此秒数会增加一个额外的问题。

只需删除其中一个调用startTimer()


推荐阅读