I previously asked for a review at Code Review: count to target with javascript, and it was a great help. I'm now looking for comments on the extended version. This code very simply counts in the direction of a particular target number, with the count slowing down as the target gets nearer. The target number is stored in a nearby file and is often modified by other processes (so this should display a gradual change towards the new number.
Please be as brutal as you like with ways to improve the code or the algorithm (I'm aware there should be comments) - I'm a recreational programmer and would like to be improving my skills. This is absolutely my first use of AJAX and I'm amazed it worked at all :)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Count to a particular target</title>
</head>
<body>
<h1 id="myDiv">Starting</h1>
<script type="text/javascript">
currentValue = 100;
targetValue = 1000;//as an initialisation value
ticks=0;
function count() {
ticks++;
if (ticks==100)
{
ticks=0;
loadtarget();
}
if (currentValue == targetValue) return;
currentValue < targetValue ? currentValue++ : currentValue--;
document.getElementById('myDiv').innerHTML = 'Total wordcount:'+ currentValue.toString();
setTimeout(count,Math.max(20, 1000 - Math.abs(currentValue - targetValue))/10);
}
function loadtarget()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
targetValue=xmlhttp.responseText;
}
}
xmlhttp.open("GET","target.txt",true);
xmlhttp.send();
}
loadtarget();
count()
</script>
</body>
</html>