Una classe countDown in Javascript

Lunedì 13 Ottobre, 2008

Nel post 3D CountDown con FIVe3D (vedi anche How I Did It: scrivere un countdown in Flash), veniva proposta una classe per la creazione di un oggetto CountDown in Actionscript, eccone una versione simile in Javascript:

JavaScript:
  1. /**
  2. * CountDown Class
  3. *
  4. * @author        Giovambattista Fazioli
  5. * @email         g.fazioli@undolog.com
  6. * @web           http://www.undolog.com
  7. *
  8. * @param    dd   (string) 'month day, year'
  9. *
  10. */
  11. function countDown( dd ) {
  12.     // init target time
  13.     var target            = new Date( dd );
  14.     this.targetTime        = target.getTime();
  15.    
  16.     /**
  17.      * refresh countdown
  18.      */
  19.     this.refresh = function() {
  20.         var today                 = new Date();
  21.         var currentTime           = today.getTime();
  22.         // time left
  23.         this._leftMilliseconds    = (this.targetTime - currentTime);
  24.         this._leftSeconds         = Math.floor( this._leftMilliseconds / 1000 );
  25.         this._leftMinutes         = Math.floor( this._leftSeconds / 60 );
  26.         this._leftHours           = Math.floor( this._leftMinutes / 60 );
  27.         // no module
  28.         this.leftDays             = Math.floor( this._leftHours / 24 );
  29.         // for print
  30.         this.leftMilliseconds     = this._leftMilliseconds % 1000;
  31.         this.leftSeconds          = this._leftSeconds % 60;
  32.         this.leftMinutes          = this._leftMinutes % 60;
  33.         this.leftHours            = this._leftHours % 24;
  34.     }
  35.     this.refresh();
  36. }

Esempio

JavaScript:
  1. var cd = new countDown( '1 1, 2009' );
  2. // mostra quanti giorni, ore, minuti, secondi e millisecondi al primo gennaio 2009
  3. document.write( cd.leftDays + "," + cd.leftHours + "," + cd.leftMinutes + "," + cd.leftSeconds + "," + cd.leftMilliseconds );

Post correlati