Timer logic — Timer ticker

We need a universal time interval component.

Why we need only one time interval? It’s about performance because of the mulitple timer overhead.

From the Nokia’s best practice:

Use one timer to animate multiple elements at the same time

Ticker

 1// the ticker module
 2;(function() {
 3  // declare a global variable 'tf' (short form of twenty five)
 4  var tf = this.tf = {}
 5
 6  // a ticker is used to create global timeInterval tickers.
 7  tf.ticker = {};
 8
 9  // prepare a list for listeners which are interested to the global timer
10  tf.ticker.tickListeners = [];
11
12  // a method to add the listener to the list
13  tf.ticker.addListener = function (listener) {
14    tf.ticker.tickListeners.push(listener);
15  }
16
17  // a method to remove listener from the list
18  tf.ticker.removeListener = function (target) {
19    // loop to find the target in the array
20    for (var i=0, len= tf.ticker.tickListeners.length; i < len; i++)
21    {
22      if (tf.ticker.tickListeners[i] == target) {
23        tf.ticker.tickListeners.splice(i, 1); // remove that found target from the array
24    }
25  }
26  tf.ticker.tick = function() {
27    for (var i=0, len= tf.ticker.tickListeners.length; i < len; i++)
28    {
29      if (tf.ticker.tickListeners[i].tick != undefined)
30      {
31        tf.ticker.tickListeners[i].tick(); // call the tick function on each listener.
32      } else {
33        console.log("TickListener instance should expose a method named 'tick'");
34      }
35    }
36  }
37
38  // finally start the ticker, every second.
39  tf.globalInterval = setInterval(tf.ticker.tick, 1000);
40})();

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

overlaied image when clicked on thumbnail

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