4

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?

WholesomeGhost
  • 1,101
  • 2
  • 17
  • 31

3 Answers3

8

<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);
SactoJosh
  • 378
  • 1
  • 9
1

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

Baruch
  • 2,381
  • 1
  • 17
  • 29
1

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>
Pawan Kumar
  • 1,374
  • 7
  • 14