Una classe countDown in Javascript
lunedì 13 ottobre, 2008Nel 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:
-
/**
-
* CountDown Class
-
*
-
* @author Giovambattista Fazioli
-
* @email g.fazioli@undolog.com
-
* @web http://www.undolog.com
-
*
-
* @param dd (string) 'month day, year'
-
*
-
*/
-
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 );
-
// no module
-
this.leftDays = Math.floor( this._leftHours / 24 );
-
// for print
-
this.leftMilliseconds = this._leftMilliseconds % 1000;
-
this.leftSeconds = this._leftSeconds % 60;
-
this.leftMinutes = this._leftMinutes % 60;
-
this.leftHours = this._leftHours % 24;
-
}
-
this.refresh();
-
}
Esempio
JavaScript:
-
var cd = new countDown( '1 1, 2009' );
-
// mostra quanti giorni, ore, minuti, secondi e millisecondi al primo gennaio 2009
-
document.write( cd.leftDays + "," + cd.leftHours + "," + cd.leftMinutes + "," + cd.leftSeconds + "," + cd.leftMilliseconds );



















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=
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
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 unreturn(output)più che undocument.write()… ma è un dettaglio. Un timer, constart()estop(), renderebbe il tutto davvero completo. Complimenti e grazie per gli interessanti suggerimentiRiccardo Degni ha detto:
@Giovambattista Fazioli:
Certamente, ho inserito il document.write per una notifica immediata dei test, nella versione definitiva di produzione un
returnè d’obbligoDi niente, mi ha fatto piacere questo scambio di pareri tecnici
A presto,
Riccardo Degni
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…