Search code examples
javascripttimersetinterval

Refreshing Javascript Timer


I'm trying to making an correct/wrong application using javascript. This is my timer code:

var timeleft = 3;
var downloadTimer = setInterval(function() {
    timeleft--;
    document.getElementById("geri_sayim").textContent = timeleft;
    if (timeleft <= 0) {
        clearInterval(downloadTimer);
        alert("time is up");
    }
},1000);

I have these functions:

CreateQuestion();
CheckAnswer();
isConfirm();

When I add this timer into CreateQuestion(), it works. But I want to stop this timer when the user clicks an answer button. For this reason I add this code into CheckAnswer()

clearInterval(downloadTimer);

But when I do this, the application doesn't work, and neither does the timer. Basically I want to countdown from 3 for each question. What's my mistake?


Solution

  • This solution works for what you want to achieve:

    HTML

    <body onload="createQuestion();">
    <p id="my-question"></p>
    <p id="time-left">3</p>
    <button onclick="checkAnswer();">Check Answer</button>
    


    JavaScript

    var timeleft = 3;
    var myTimer;
    
    function createQuestion() {
        // You create your question..
        document.getElementById("my-question").innerHTML = "Do you know the answer to this question?";
        // ..and start the timer..
        myTimer = setInterval(function() {
        timeleft--;
        document.getElementById("time-left").textContent = timeleft;
        if (timeleft <= 0) {
            clearInterval(myTimer);
            alert("Time is up!");
        }
        },1000);
    }
    function checkAnswer() {
        // Pause the time!
        clearInterval(myTimer);
        alert("Time paused!");
    }
    function isConfirm() {
        // Whatever other code you wrote for this function
    }