Timer logic — Core

The Core component that makes use of the timer and DOM to control the count down.

 1;(function() {
 2  var TwentyFiveTimer = (function() {
 3    function TwentyFiveTimer(element) {
 4      this.counter = 0; // the counting variable
 5      this.element = element; // the element to show timer result
 6      this.reset();
 7    }
 8
 9    TwentyFiveTimer.prototype.reset = function() {
10      tf.ticker.removeListener(this); // remove self instance from the ticker list.
11      this.counter = 60 * 25; // 25 minutes;
12      $(this.element).html("25:00");
13    }
14
15    // the tick function, core logic of the app
16    TwentyFiveTimer.prototype.tick = function() {
17      this.counter -= 1; // the real counting down.
18      if (this.counter < 0) this.counter = 0; // dont forget to set the boundary.
19
20      // the minute
21      var minute = Math.floor( this.counter / 60 );
22      if (minute < 10) minute = '0' + minute;
23
24      // the second
25      var second = this.counter % 60;
26      if (second < 10) second = '0' + second;
27
28      // display it, finally.
29      $(this.element).html(minute + ":" + second);
30    }
31    TwentyFiveTimer.prototype.start = function() {
32      tf.ticker.addListener(this); // add self instance to the ticker list, so we will get tick invoked.
33    }
34
35    TwentyFiveTimer.prototype.restart = function () {
36      this.reset();
37      this.start();
38    }
39
40    // finish the class implementation, at last we return it to the outter scope.
41    return TwentyFiveTimer;
42})();
43  // and set it to our global scope to let other module to use it.
44  tf.TwentyFiveTimer = TwentyFiveTimer;
45})();

jQuery ready function is updated.

 1// jQuery ready callback
 2$(function() {
 3  // default page transition
 4  $.mobile.defaultPageTransition = 'slide'
 5
 6  $('#timer').html('25:00');
 7
 8  var timer = new tf.TwentyFiveTimer($('#timer'));
 9  timer.start();
10
11  // handle the reset button
12  $('#reset').click( function(e){
13    timer.restart();
14  });
15
16});

What’s next? We’re going to take a look at “Timer logic — Time’s up”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content