JavaScript timer for a quiz

15,638

Solution 1

<div id="count">Start</div>

var count = 15;
var interval = setInterval(function(){
  document.getElementById('count').innerHTML=count;
  count--;
  if (count === 0){
    clearInterval(interval);
    document.getElementById('count').innerHTML='Done';
    // or...
    alert("You're out of time!");
  }
}, 1000);

Solution 2

Initialize the variable 'sec' with timeout time in seconds. Call setInterval() which has 2 parameters, 1st is the method name and 2nd parameter is interval between invoking the method mentioned in 1st parameter.

var sec = 15;
var time = setInterval(myTimer, 1000);

function myTimer() {
    document.getElementById('timer').innerHTML = sec + "sec left";
    sec--;
    if (sec == -1) {
        clearInterval(time);
        alert("Time out!! :(");
    }
}
Time : <span id="timer"></span>

Solution 3

Here's a basic example of a countdown timer

var count = 15;
var timer = setInterval(function() {
  console.log(count);
  count--;
  if(count === 0) {
    stopInterval()
  }
}, 1000);

var stopInterval = function() {
  console.log('time is up!');
  clearInterval(timer);
}

Repl: https://repl.it/I2C6

Share:
15,638
WholesomeGhost
Author by

WholesomeGhost

Matt, 19

Updated on July 03, 2022

Comments

  • WholesomeGhost
    WholesomeGhost almost 2 years

    I am making a quiz game for a project in HTML and JavaScript. On every question, the player has 15 seconds to answer. I managed to do it like this:

    <body onload="setTimeout(Timer,15000)">
    

    and then in Js:

    function Timer()
        {
             alert("You are out of time!");
        }
    

    However, I want to be able to display how much time the player has left in a <p> tag. How could I do that?