Search code examples
javascriptcountercountdown

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 ?


Solution

  • 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>
    

    ......