Timer.js: a Javascript class similar to the Actionscript 3 one

As I said in my first post, I’m studying Actionscript 3 (from the scratch… I never used it before). One thing that I discovered is that since as3, has been introduced the Timer class, which purpose is to replace the setInterval() function (still available, but to be considered deprecated due to its limits) and provide a more flexible, elegant and OOP way to handle recursive actions (ie: calling N times the same method(s) at a given interval, generally to produce an animation).  Like Actionscript, Javascript offers the setInterval() function, but it lacks a cool class like Timer, so just for fun (but maybe in the future i can use it in production) I’ve realized a similar js class that offers more or less the same functionalities.

It can be instantiated in this way:

var timer = new Timer({
    id: "mytimer", // required!
    delay: 400, // optional (default to 1000)
    steps: 10 // optional (default to 0 = executes always)

In the example above the timer object has the id of “mytimer” and it will be executed one times every 400 milliseconds for 10 times in total. The Timer.js class takes one argument as a configuration object that must specify an id for the timer and optionally how many times it should be triggered (steps) and the time that should be pass from a trigger to the other (delay). Timer.js, differently from its as3 counterpart doesn’t dispatch an its own event every time it is triggered… so you can’t subscribe for example a listener for a Timer.is event in a traditional way (something like timer.onEvent = function()), but it has its own methods for such event handling. In detail it can accept N callback functions that will be executed on:

  • each step
  • when the timer is stopped
  • when the timer is resetted
  • when the timer has finished (it has reached the prefixed number of steps)

The (auto descriptive) methods for the events handling are the following:

  • addStepListener(listener) / removeStepListener(listener)
  • addStopListener(listener) / removeStopListener(listener)
  • addResetListener(listener) / removeResetListener(listener)
  • addEndListener(listener) / removeEndListener(listener)

The core methods are instead:

  • start()
  • stop()
  • reset()

and finally there are 2 utilities methods:

  • isActive()
  • getCurrentStep()

The source code plus an html page to test the Timer can be downloaded here: timerjs.zip