Hermes Hermes - 5 months ago 27
jQuery Question

Simple countdown timer with a value

I want to use a simple countdown timer. Firsty I define a duration I send the duration kind of seconds and minutes to span text. Also I define a value. For example value is 20. I want to decrease the value in every minute. When the value is equal zero function will be finished. I hope I could have explained enough.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<div>Remain <span id="time"></span> minute</div>
<script>
function startTimer(duration, text, value) {
var timer = duration, minute, second, value;
setInterval(function () {
minute= parseInt(sure / 60, 10);
second= parseInt(sure % 60, 10);
if(minute<10){
minute="0"+minute;}
else{
minute=minute;}
if(second<10){
second="0"+second;}
else{
second=second;};
text.text(minute+ ":" + second);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload=function () {
var duration= 1200, text = $('#time'), value=10;
minute= parseInt(sure / 60, 10);
second= parseInt(sure % 60, 10);
if(minute<10){
minute="0"+minute;}
else{
minute=minute;}
if(second<10){
second="0"+second;}
else{
second=second;};
$("#time").text(minute+":"+second);
startTimer(duration, text, value);};
</script>
</body>
</html>

Answer
  • Use a variable elapsed to keep track of how many seconds have past
  • Deduct value when elapsed is divisible by 60, meaning a minute have past
  • Call run once per second as long as value is greater than 0
  • Also, you don't need to repeat the code in startTimer and onLoad

function startTimer(duration, text, value) {
  var timer = duration,
    minute, second, value, elapsed = 0;

  var run = function() {
    minute = parseInt(timer / 60, 10);
    second = parseInt(timer % 60, 10);
    if (minute < 10) {
      minute = "0" + minute;
    } else {
      minute = minute;
    }
    if (second < 10) {
      second = "0" + second;
    } else {
      second = second;
    };
    text.text(minute + ":" + second);
    if (--timer < 0) {
      timer = duration;
    }
    elapsed++;
    if (++elapsed % 60 == 0) value--;
    if (value <= 0) {
      clearInterval(timerId);
    }
    $("#time").text(minute + ":" + second);
    $('#val').text(value);

    if (value > 0) {
      setTimeout(run, 1000);
    }
  };
  
  run();
}

window.onload = function() {
  var duration = 1200,
    text = $('#time'),
    value = 10;

  startTimer(duration, text, value);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Remain <span id="time"></span> minute</div>
<div>Value <span id="val"></span>
</div>

Comments