Archive

Posts Tagged ‘game’

JavaScript Timer Countdown

August 2nd, 2011 No comments

Working on a new game. Wrote this TimerCountdown object for a Timer in the game. Works pretty well, still not fully tested.

var TimerCountdown = function() {
  var oOnZero     = function(){},
      oOnUpdate   = function(){},
      oTimer,
      iCurTime    = 0;
 
  function CreateTimer() {
    oTimer = setInterval(IterateTimer, 1000)
  }
 
  function DestroyTimer() {
    clearInterval( oTimer );
  }
 
  function IterateTimer() {
    iCurTime = iCurTime - 1;
    oOnUpdate({
      Seconds: iCurTime,
      Minutes: parseInt( iCurTime / 60 ),
      Hours: parseInt( iCurTime / 60 / 60 )
    });
 
    if( iCurTime <= 0 ) {
      DestroyTimer();
      oOnZero();
    }
  }
 
  return {
    SetTime: function( iSeconds ) {
      iCurTime = iSeconds;
    },
    Start: function() {
      CreateTimer();
    },
    Stop: function() {
      DestroyTimer();
    },
    Time: function() {
      return iCurTime;
    },
    Add: function( iSeconds ) {
      iCurTime = iCurTime + iSeconds;
    },
    Subtract: function( iSeconds ) {
      iCurTime = iCurTime - iSeconds;
    },
    OnUpdate: function( cbFunction ) {
      oOnUpdate = cbFunction;
    },
    OnZero: function( cbFunction ) {
      oOnZero = cbFunction;
    }
  };
};
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags: , ,