JQuery Timer Library


I have been working on game development for the past month. Building game logic is pretty fun, but the need for a good JavaScript timer was needed. Having done a few searches online, I've found Matt Schmidt JQuery Timer plugin v0.1. Out of the box it does everything I want, but there was one issue that was becoming evident. 


JQuery Timer uses JavaScript setInterval which basically recursively calls the code in the block as shown below

         $.timer(1000, function (timer) {
                console.log(Hello World!');
            });


In the above block of code, Hello World! is outputted to the console every minute… What if we wanted to display Hello World only once?


         $.timer(1000, function (timer) {
                console.log(Hello World!');
            timer.stop();
            });

The above block of code would terminate the timer after the block of code is executed. The problem with this is
1.  You need an extra function just to terminate
2.  You don’t always remember to terminate (especially n00bs).

It’s really not that big of an issue, but I decided to implement a flag (type flag). This basically gives the developer the choice between using setInterval (recursive execution) or setTimeout (executes once).




The above timer code would be:
         $.timer(1000, function (timer) {
                console.log(Hello World!');
           },'timeout');

The default timer settings is setTimeOut therefore the following block can be written as:

         $.timer(1000, function (timer) {
                console.log(Hello World!');
           });


e.g

$.timer(1000, function (timer) {
     console.log(Hello World!');
     timer.stop();
   },'interval');

e.g. Show an alert box after 1 second and show another after 3 seconds
var second = false;
 $.timer(1000, function (timer) {
     if (!second) {
         alert('First time!');
         second = true;
         timer.reset(3000);
     }
     else {
         alert('Second time');
         timer.stop();
     }
 },'interval');


The library can be found here : http://code.google.com/p/ferron-jquery-timer/

Comments

Popular posts from this blog

JavaScript Module Pattern: 2 Forms

Pseudo-Random UUID Generation with mask support

Mocking Ajax with the JQuery Mockjax Library