Légende : Fonction, argument, variables, objet, fonction JQuery
/**
* formatTime : Format time to show date from iStartDate to iNow in H, M, S
* @param iNow
* @returns {string}
*/
function formatTime(iNow) {
var iStartDate = 1402492480610;
var iStartInSeconds = parseInt(iStartDate / 1000);
var iNowInSeconds = parseInt(iNow / 1000);
var iDiffSeconds = iNowInSeconds - iStartInSeconds;
var iDiffMinutes = (parseInt(iDiffSeconds / 60)) % 60;
var iDiffHours = (parseInt(iDiffSeconds / 3600));
var iDiffSecondsModulo = iDiffSeconds % 60;
return " Sur la toile depuis : " + iDiffHours + " H " + iDiffMinutes + "
M " + iDiffSecondsModulo + " S";
}
$('#time').html(formatTime($.now()));
setInterval(function () {
$('#time').html(formatTime($.now()));
}, 1000);
La fonction JQuery .now() renvoie en ms le temps qui nous sépare du 1er Janvier 1970 ( (10^11
chiffres !)
Il suffit de soustraire le now à la date actuelle (en arondissant à la seconde), par
le now() généré à lacr éation du site. L'écart s'agrandit toutes les secondes grâce au setInterval
qui rafraîchit le compteur.