0

So, I want to create a timer and this is the code I have so far.

<!DOCTYPE html>

<html>

<head>

  <title>WIP</title>
  <meta charset="UFT-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

  <script>
    function timerCreate(minutes, seconds) {
      var i = 0;
      var f = 0;
      $("#timerText").text((minutes - f) + ":" + (seconds - i));
      i++;
      do {
        interval = setInterval(function() {
          $("#timerText").text((minutes - f) + ":" + (seconds - i));
          i++;
          if (i >= seconds) {
            clearInterval(interval);
            setTimeout(function() {
              $("#timerText").text((minutes - f) + ":" + "0");
            }, 1000);
            if (minutes > 0) {
              f++;
            }
          }
        }, 1000);
      } while (!(f = minutes));
    }
  </script>

</head>

<body onload='timerCreate(5, 4)'>

  <div id="timerText">Timer</div>

</body>

</html>

Please run the code to see what it does. I don't understand why it does this. Could anyone help? Also, although I fell like I'll eventually get it, this code seems to me way too all over the place. If you agree, I'd be really grateful if you could link me to some code for a timer. Either way, I'd really like it if you could explain to me what I'm doing wrong.

Thanks so much to anyone who answers. :-)

cabralpinto
  • 1,814
  • 3
  • 13
  • 32

2 Answers2

1

This is clearly a job for a recursive function. First you want timerCreate(5, 4).
What happens next, is that 1 second later you could call timerCreate(5, 3).
So it's obvious to let the function call itself ( = recursive function), each time with 1 fewer second.

Notice the modulo operator % versus the / operator. What % does, is tell you what's left after you do a division.

example:

91 / 60 = 1 + 31/60
Math.floor(91/60) = 1;
91%60 = 31;

So dividing and flooring gives you minutes; modulo gives you seconds.

Here is something I just wrote, based on my first instincts concerning this problem (without looking at other timers; and clearly there are plenty of timers to be found online).

<input id="m" placeholder="minutes" value="1">
<input id="s" placeholder="seconds" value="17">
<input type="button" value="Start" onclick="startTimer()">
<input type="button" value="Stop" onclick="stopTimer()">
<hr>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var timer;
function displayTimer(m, s) {
  $('#m').val(m);
  $('#s').val(s);
}

function stopTimer() {
  clearTimeout(timer);
}

function startTimer() {
  var m = Number($('#m').val());
  var s = Number($('#s').val());
  timerClick(m, s);
}

function finishTimer() {
  alert('finished!');
}

function timerClick(m, s) {
  // convert into seconds
  var seconds = 60*m + s;
  // display timer, unless the timer has been set off
  if(timer) {
    displayTimer(m, s);
  }
  if (m == 0 && s == 0) {
    finishTimer();
    return true;
  } 
  // remove one second
  seconds--;
  // call this function again
  timer = setTimeout(function() {
      timerClick(Math.floor(seconds / 60), seconds % 60);
    },
    1000
  );
}
</script>
Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17
1

Here is an example to your code:

HTML:

<div id="timerText">Timer</div>

JavaScript Code:

var timerElement = $('#timerText');

function timerCreate(minutes, seconds) {
    var finalTimerTime = getFinalTime(minutes, seconds);

    // starts run timer every second and gets handler to the timer, so it can be stopped when time gets
    // final time
    var timer = setInterval(function () {
        var currentTime = new Date();
        if (currentTime > finalTimerTime) {
            clearInterval(timer);
            console.log('Done');
        } else {
            printTimer(new Date(finalTimerTime - currentTime));
        }
    }, 1000);

    printTimer(new Date(finalTimerTime - new Date()));
}

// prints timer valud
function printTimer(finalTimerTime) {
    timerElement.text(finalTimerTime.getMinutes().timePadding() + ' : ' + finalTimerTime.getSeconds().timePadding());
}

// adds leading prefix for presenting time in '0X' format
Number.prototype.timePadding = function() {
    return this < 10 ? '0' + this : this;
}

// gets final time of the timer
function getFinalTime(minutes, seconds) {
    var finalTimerTime = new Date();
    finalTimerTime.setMinutes(finalTimerTime.getMinutes() + minutes);
    finalTimerTime.setSeconds(finalTimerTime.getSeconds() + seconds);

    return finalTimerTime;
}

// starts timer
$(function () {
    timerCreate(5, 4);
});

Here is an working example of the code

Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
  • This is creative, but the time looks a little weird at times like 1:09 as `finalTimerTime.getSeconds()` returns with `9` instead of `09`. Thus making the output `1:9`. – HPierce Sep 08 '15 at 15:58
  • 1
    @HPierce. I added timePadding function that takes care of leading '0'. – Vlad Bezden Sep 08 '15 at 17:22