Как я могу остановить функцию таймера, если тест заканчивается до истечения времени? Javascript - PullRequest
0 голосов
/ 02 мая 2020

У меня все работает как надо, за исключением того, что я пробовал миллион разных вещей и не смог заставить функцию таймера прекратить обратный отсчет, если тест завершится до истечения 60 секунд.

    //total score var that is defined in local storage and question number var that will be incremented later on
var totalScore = 0, 
    questionNumber = 0,
    i = 0;
// questions object
    allQuestions = [{
        question: "What do you call a variable with multiple boolean values?",
        choices: ["variable", "object", "array", "let"],
        correctAnswer: "array"
    },
    {
        question: "A useful tool for debugging during development is_______.",
        choices: ["wrench", "Chrome dev tools", "Visual Studio Code", "keyboard"],
        correctAnswer: "Chrome dev tools"
    },
    {
        question: "Where will you find most of the answers to the questions you will have in your coding career?",
        choices: ["Teachers", "Coworkers", "User manual", "The Internet"],
        correctAnswer: "The Internet"
    },
    {
        question: "What should you do when using git before you push a project to the repository?",
        choices: ["pull", "bop it", "save it", "close it"],
        correctAnswer: "pull"
    }
];

var counterValue = 60;



var mainContent = $('#mainContent'); 
//logic if correct answer is chosen
function correctGuess() { 
    totalScore ++; 
    questionNumber ++;

    var updatePage = question(questionNumber);

    localStorage.setItem("scoreCount", totalScore);

    $('#mainContent').html(updatePage); 

    if(questionNumber < 4){
        var updatePage = question(questionNumber);

        $('#mainContent').html(updatePage); 

    }


};
//logic if incorrect answer is chosen
function incorrectGuess() {
    counterValue -= 5;
    totalScore = 0;
    questionNumber ++;

    var updatePage = question(questionNumber);

    $('#mainContent').html(updatePage);

    };

//starting screen
        function welcome() {
    mainContent.html('<h2>Welcome to the Code Quiz!</h2>' + '<br />' + 
    '<h5>If you think you have what it takes, go ahead and click the start button to see how you do!</h5>' 
    + '<button type="button" class="btn btn-primary" id="startQuizBtn">Start Quiz!</button>');
    document.getElementById("startQuizBtn").addEventListener("click", function() {question(i)});
//timer function
    document.getElementById("startQuizBtn").addEventListener("click", function() {timer()})
};

function timer() {
var timer = setInterval(function(){
    counterValue -= 1;
    $("#timer-value").html(counterValue)

    if (counterValue <= 0) {
        clearInterval(timer)
        displayScore()
    }
},1000)
}


//loads start page to begin with
window.onload = function () {
    this.welcome();
};
//logic to run through questions object
function question(i) {
    if (i < 4) {
    mainContent.html('<div id="questionDiv">' +
        '<h2>Question ' + (i + 1) + '<h2>' +
        '<h3>' + allQuestions[i].question + '</h3>' +
        '<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[0] + '" checked="yes">' + allQuestions[i].choices[0] + '</input>' + '<br />' +
        '<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[1] + '">' + allQuestions[i].choices[1] + '</input>' + '<br />' +
        '<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[2] + '">' + allQuestions[i].choices[2] + '</input>' + '<br />' +
        '<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[3] + '">' + allQuestions[i].choices[3] + '</input>' + '<br />' +
        '<button type="button" class="btn btn-primary" id="submitButton">Submit</button>' + '</div>' );
    } else {
        chooseNextScreen();
    };

//submit button at the bottom of the questions
    $('#submitButton').on('click', function() {

        if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer && i < 4) {
            correctGuess();
        } else {
            incorrectGuess();
        } 

    });
};

//logic to decide what screen to append next
 function chooseNextScreen(){
    if (questionNumber < 4) {
        question();
    } else {
        displayScore();
    }
    };

// end screen of quiz
function displayScore() {
    //Text, form and button on end page
    $('#mainContent').html('<h2>Well Done!</h2>' + '<h4> You scored ' + totalScore + '!</h4>' + '<h4>Please enter your name for the end screen</h4>' +
    '<hr />' + '<form>' + '<input class="form-control" id="initialsBox" type="text" placeholder="Your Name">' + '<button type="button" class="btn btn-primary" id="hiScoreSubmitBtn">Submit</button>' + '</form>');
    // Submit button on end screen of quiz
    $('#hiScoreSubmitBtn').on('click', function(event) {
        localStorage.setItem(initialsBox[0].value, totalScore);
        mainContent.html('<h1>' + initialsBox[0].value + ' scored a ' + totalScore + '!' + '</h1>');
    });
    var initialsBox = $("#initialsBox");
};
//calls function for quiz to run

question(questionNumber);

Вот HTML

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <title>Code Quiz</title>
    <link rel="stylesheet" type="text/css" href="assets/style.css" />

</head>


<body>
    <!--Top row heading of title and time left-->
    <div class="row">
        <div class="col">
            <h1 id="code-quiz">Code Quiz!</h1>
        </div>
        <div class="col">
        <h3 id="timer">Time Left: <span id="timer-value"></span></h3>
        </div>
    </div>
    <!--Main Content-->
    <div class="container">
        <div id="headingLine" class="row main-heading">
            <div class="classname" id="id"></div>
        </div>
        <div class="row">
            <div class="col" id="mainContent">

            </div>
        </div>

      </div> 
      <!--Script Tags-->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
      <script src="assets/script.js"></script>
</body>


</html>

Я не могу помочь, но чувствую, что ответ прямо передо мной, но я смотрел на это часами.

1 Ответ

0 голосов
/ 02 мая 2020
document.getElementById("startQuizBtn").addEventListener("click", ()=>{
   var counterVal = 5;
   timer=setInterval(function() {
     counterVal=counterVal-1;
    console.log(counterVal)
    if(counterVal==0){
    clearInterval(timer)
    }
    },1000)
})
...