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

4 commenti a: “Una classe countDown in Javascript”

  1. getAvatar 1.0 Martedì 14 Ottobre, 2008 alle 16:03
    Riccardo Degni ha detto:

    Ciao Giovambattista,
    trovo molto interessante questa soluzione Javascript, perchè è semplice e leggera. Da amante dello scripting, ho apportato alcune modifiche al tuo codice che ti posto di seguito:

    function countDown( dd ) {
        // init target time
        var target            = new Date( dd );
        this.targetTime       = target.getTime();
    
        /**
         * refresh countdown
         */
        this.refresh = function() {
            var today             = new Date();
            var currentTime       = today.getTime();
            // time left
            this.leftMilliseconds = this.targetTime - currentTime;
            this.leftSeconds      = Math.floor(this.leftMilliseconds / 1000);
            this.leftMinutes      = Math.floor(this.leftSeconds / 60);
            this.leftHours        = Math.floor(this.leftMinutes / 60);
            this.leftDays         = Math.floor(this.leftHours / 24);
            this.render();
        };
    
        this.render = function() {
            this.leftMilliseconds = this.ms = this.leftMilliseconds%1000;
            this.leftSeconds = this.s = this.leftSeconds%60;
            this.leftMinutes = this.m = this.leftMinutes%60;
            this.leftHours = this.h = this.leftHours%24;
            this.d = this.leftDays;
        };
    
        this.output = function(_format) {
            var format = _format.split(' ') || 'd h m s ms', output = '';
            // alert(fn); commentato da =undo= :D
            for(var t in format) {
                if(this[format[t]]) output += this[format[t]] + ((t!=format.length-1) ? ', ' : '');
            }
            document.write(output);
        };
    
        this.refresh();
    }
    

    In sostanza l’aggiunta più corposa è rappresentata dal metodo output, che permette di stampare il countdown con il formato desiderato dall’utente (in una maniera molto simile a come accade nel PHP).
    Se ad esempio si volessero stampare il giorno, l’ora, i minuti, i secondi ed i millisecondi mancanti tramite il nostro countdown, si potrebbe procedere nel seguente modo, senza ogni volta ricorrere al richiamo delle proprietà interne della nostra classe:

    var cd = new countDown( '1 1, 2009' );
    cd.output('d h m s ms');
    

    Il metodo “render” si occupa infine del “normalizzare” il formato dei numeri.

    Un’altra aggiunta interessante potrebbe essere quella di un metodo “start”, che richiama il metodo output periodicamente in modo che sembri un vero e proprio countdown (countdown che potrà essere fermato dal rispettivo metodo “stop”).

    Riccardo Degni

  2. getAvatar 1.0 Martedì 14 Ottobre, 2008 alle 22:27
    Giovambattista Fazioli ha detto:

    @Riccardo Degni: davvero una bella variante, bravo! Interessante soprattutto la tecnica per formattare l’output: ingegnosa e sottile! Nel metodo output() metterei al limite un return(output) più che un document.write()… ma è un dettaglio. Un timer, con start() e stop(), renderebbe il tutto davvero completo. Complimenti e grazie per gli interessanti suggerimenti :)

  3. getAvatar 1.0 Mercoledì 15 Ottobre, 2008 alle 12:45
    Riccardo Degni ha detto:

    @Giovambattista Fazioli:

    Nel metodo output() metterei al limite un return(output) più che un document.write()

    Certamente, ho inserito il document.write per una notifica immediata dei test, nella versione definitiva di produzione un return è d’obbligo ;)

    Complimenti e grazie per gli interessanti suggerimenti :)

    Di niente, mi ha fatto piacere questo scambio di pareri tecnici :)

    A presto,
    Riccardo Degni

  4. getAvatar 1.0 Giovedì 20 Novembre, 2008 alle 22:31
    Giovambattista Fazioli ha detto:

    Aggiornamento: su Microsoft Internet Explorer 7 la data in formato numerico, tipo "3 5, 2008", produce errore. Per eliminarlo basta inserire il “mese” nel formato 3 lettere in inglese: Jan, Feb, Mar, etc…

Lascia un commento

TAG XHTML permessi: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Usa <pre> per racchiudere codice