Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set one minute counter in javascript?

In my project ,I have list of questions, for every question have three option answers.

After see the question if i want answer that question means click "show answer" button . when I click button ,counter starts for one minute after one minute error will show .

can any one help ?

like image 866
Karthick Terror Avatar asked Jul 31 '11 23:07

Karthick Terror


People also ask

Does JavaScript have a timer?

JavaScript provides two functions to delay the execution of tasks. These are timer functions.


2 Answers

You could use something like this:

function gameLost() {
  alert("You lose!");
}
setTimeout(gameLost, 60000);

UPDATE: pass function reference to setTimeout() instead of code string (did I really write it that way? O_o)


EDIT

To display the timer too (improved version, thanks to davin too):

<button onclick="onTimer()">Clickme</button>
<div id="mycounter"></div>
<script>
i = 60;
function onTimer() {
  document.getElementById('mycounter').innerHTML = i;
  i--;
  if (i < 0) {
    alert('You lose!');
  }
  else {
    setTimeout(onTimer, 1000);
  }
}
</script>

......

like image 141
redShadow Avatar answered Sep 22 '22 09:09

redShadow


function timedOut() {
    alert("Some error message");
}

// set a timer
setTimeout( timedOut , 60000 );

That basically sets a timer that will execute the given function after 60.000 miliseconds = 60 seconds = 1 minute

Edit: here's a quick, imperfect fiddle that also shows the countdown http://jsfiddle.net/HRrYG

function countdown() {
    var seconds = 60;
    function tick() {
        var counter = document.getElementById("counter");
        seconds--;
        counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
        if( seconds > 0 ) {
            setTimeout(tick, 1000);
        } else {
            alert("Game over");
        }
    }
    tick();
}

// start the countdown
countdown();
like image 31
Flambino Avatar answered Sep 24 '22 09:09

Flambino