0

I created a countdown in jQuery but I have an issue. When the count reaches 01:00 it gets stuck instead of continuing on to 00:59 with minute of 0.

var start = $('#start');
var countMinutes = 2;

var timer;
start.on('click', function(event) {
  event.preventDefault();
  new Timer(function(val, countMinutes) {
    timerMsg = (countMinutes >= 10 ? countMinutes : '0' + countMinutes) + ':' + (val >= 10 ? val : '0' + val);
    time.text(timerMsg);
  });
});

function Timer(callback, val, m) {
  val = val || 59;
  m = countMinutes;
  timer = setInterval(function() {
    callback(val, m);
    if (val-- <= 0) {
      m -= 1;
      if (m < 1 && val <= 0) {

        clearInterval(timer);
      }
      countMinutes = 0;
      val += 60;
    }
  }, 1000);
}

my html.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="timer"><span id="time">10:00</span></h1>
<a href="#" id="start">Start</a>
Emud Ron
  • 47
  • 1
  • 8

2 Answers2

3

Change

if (m < 1 && val <= 0) {

to

if (m < 0 && val <= 0) {
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
-3

var countMinutes = 2;
var timer;

$('#start').on('click', function(event) {
  event.preventDefault();
  new Timer(function(val, countMinutes) {
    timerMsg = (countMinutes >= 10 ? countMinutes : '0' + countMinutes) + ':' + (val >= 10 ? val : '0' + val);
    $('#time').text(timerMsg);
  });
});

function Timer(callback, val, m) {
  val = val || 59;
  m = countMinutes;
  timer = setInterval(function() {
    callback(val, m);
    if(val-- <= 0) {
      m -= 1;
      if(m < 0 && val <= 0) {

        clearInterval(timer);
      }
      countMinutes = 0;
      val += 60;
    }
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1 id="timer">
  
<span id="time">10:00</span></h1>

<a href="#" id="start">Start</a>
nazimboudeffa
  • 939
  • 6
  • 20
  • It would probably be a good idea to explain what you changed, and why. Just copy/pasting code isn't really teaching anyone anything :-) – Martin Tournoij Nov 16 '16 at 04:34
  • you're right, as the code is working i didn't wanted to add more comments then the snippet, the problem with this code is that we can't understand the meaning of each variable by just reading it – nazimboudeffa Nov 16 '16 at 11:36
  • when you enter the Timer function, val =59 or its actual value and m= countMinutes as a global variable, the callback function sets the text to be displayed every second seted by the setInterval then you have the if then else that just evalute if the timer has arrived to 0 or not but i don't understand the last two lines countMinutes = 0; and val +=60 – nazimboudeffa Nov 16 '16 at 11:44