Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple clock that counts down from 30 seconds and executes a function afterward [closed]

Tags:

javascript

I have a game that gives a time limit and I need to display a countdown clock for the users and stop the game once the time is up such as 30 seconds. How can I do this in javascript?

like image 882
thenengah Avatar asked Dec 14 '10 04:12

thenengah


People also ask

What is countdown function on timer?

A countdown timer can be defined as a virtual clock that counts down from a certain date or number to indicate the end or beginning of an offer or event.


2 Answers

Use setInterval to set up a timer. Within this timer, you can update some text in your page and when the time is up, you can call whatever function you want:

var timeLeft = 30;
    var elem = document.getElementById('some_div');
    
    var timerId = setInterval(countdown, 1000);
    
    function countdown() {
      if (timeLeft == -1) {
        clearTimeout(timerId);
        doSomething();
      } else {
        elem.innerHTML = timeLeft + ' seconds remaining';
        timeLeft--;
      }
    }
<div id="some_div">
</div>
like image 90
casablanca Avatar answered Nov 15 '22 08:11

casablanca


Check out setTimeout and setInterval:

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

like image 36
zsalzbank Avatar answered Nov 15 '22 06:11

zsalzbank