Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript timer for a quiz

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?

like image 637
WholesomeGhost Avatar asked Jan 04 '23 22:01

WholesomeGhost


2 Answers

<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);
like image 162
SactoJosh Avatar answered Jan 06 '23 10:01

SactoJosh


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

like image 25
Baruch Avatar answered Jan 06 '23 12:01

Baruch