Programmation JavaScript/Programmer en deux minutes/Compteur en temps réel

Un livre de Wikilivres.

Document HTML :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="fr">
   <head>
   </head>
 
   <body>
	<div id="compteur"></div>

	<script type="text/javascript">
          /* Copier-coller le javascript ici,  
           * ou créez un fichier *.js et déclarez-le dans ce document html.
           */
	</script>

   </body> 
</html>


Le JavaScript peut sembler long mais est très simple : il exécute la fonction RunWarCost() qui se ré-exécute toutes les 100 millisecondes (window.setTimeout()).

Au passage cette fonction calcule le prix et l'affiche dans la division "compteur" du document. (document.getElementById().innerHTML)

Si vous êtes un utilisateur enregistré de Wikipédia, vous pouvez personnaliser votre JavaScript pour ajouter à votre interface plein de choses, dont bien sûr ce compteur. (voir Gadget-WarCost.js)
//////////////////////Start CUSTOMIZATION//////////////////////
//// Le budget affiché :
//var Gadget_WarCost_WhichWar="US in Afghanistan since 2001";
//var Gadget_WarCost_WhichWar="US in Iraq since 2003";
//var Gadget_WarCost_WhichWar="US in Wars since 2001";
var Gadget_WarCost_WhichWar="French military budget since 2009";

//// Données :
var totalIraq = 687000000000; // total dollars allocated to Iraq War.
var startOfIraqWar = new Date("Mar 20, 2003");       // start of Iraq War.
var IraqBudgetedThrough = new Date("Sept 30, 2009"); // current budget goes to

var totalAg  = 228000000000; // total dollars allocated to Afghanistan War.
var startOfAgWar = new Date("Oct 7, 2001"); 		// start of Afghanistan War.
var AgBudgetedThrough = new Date("Sept 30, 2009");	// current budget goes to

var totalFM=186000000000;  //budget militaire français 2009 - 2014
var startOfFM=new Date("Jan 1, 2009");
var FMBudgetedThrough=new Date("Dec 31, 2014");

var separator = "'";

/////////////////End CUSTOMIZATION/////////////////

RunWarCost();  ////// Exécute la fonction principale. //

function RunWarCost()
{
	var WarCostmoney = "$";
	var OutNumberWarCost = 0;

    // Regarde quelles données afficher.
	if (Gadget_WarCost_WhichWar == "US in Wars since 2001")
	{ 
		OutNumberWarCost = calculateTotal();
	}
	else if (Gadget_WarCost_WhichWar == "US in Iraq since 2003")
	{
		OutNumberWarCost = calculateIraq();
	}
	else if (Gadget_WarCost_WhichWar =="US in Afghanistan since 2001")
	{
		OutNumberWarCost = calculateAg();
	}
	else if (Gadget_WarCost_WhichWar =="French military budget since 2009")
	{
		OutNumberWarCost = calculateFrenchMilitary();
		WarCostmoney = " €";
	}
	else alert("The value of parameter Gadget_WarCost_WhichWar is wrong.");

	var OutTextCostOfWar = number_str(OutNumberWarCost); // Formatage du nombre
	if (WarCostmoney=="$")
		OutTextCostOfWar = WarCostmoney + OutTextCostOfWar; // Symbole monétaire avant
	else
		OutTextCostOfWar = OutTextCostOfWar + WarCostmoney; // Symbole monétaire après

	var compteur = document.getElementById("compteur");
	compteur.innerHTML= "Votre compteur : " + OutTextCostOfWar + " = " + Gadget_WarCost_WhichWar; // Affiche la chaîne de caractère

	window.setTimeout(RunWarCost, 1000); ////// Ré-exécute la fonction principale dans 1 seconde.
}

function calculateFrenchMilitary()
{
	return calculateWarCost(startOfFM, FMBudgetedThrough, totalFM);
}
function calculateIraq()
{
	return calculateWarCost(startOfIraqWar, IraqBudgetedThrough, totalIraq);
}
function calculateAg()
{
	return calculateWarCost(startOfAgWar, AgBudgetedThrough, totalAg);
}
function calculateTotal()
{
	return calculateAg() + calculateIraq();
}

function calculateWarCost(startOfWar, BudgetedThrough, totalMoney)
{
	var totalMS = BudgetedThrough - startOfWar; // Durée du budget en millisecondes
	var ratePerMS = totalMoney / totalMS;       // Budget par milliseconde
	var curDate = new Date();                   // Date courante
	var diff = curDate - startOfWar;            // Millisecondes depuis le début de la guerre
	return diff * ratePerMS;                    // Coût de la guerre jusqu'à maintenant
}

function number_str(n)
{
	var x = n.toString();
	var dot = x.lastIndexOf('.');
	x = x.substr(0,dot);
	var l = x.length;
	var res = "";
	for(l-=3 ; l>0 ; l-=3)
		res = separator+x.substr(l,3) + res;
	res = x.substr(0,l+3) + res;
	return res;
}