This function should write the time spent on the page to the div.
It was working fine with a window.onbeforeunload alert.. So why isnt this working right?
<script>
function tempo1() {
var d1 = new Date();
var t_day = d1.getDate();
var t_hour = d1.getHours();
var t_min = d1.getMinutes();
var t_sec = d1.getSeconds();
alert("Started at--> " + t_day + "days, " + t_hour + ":" + t_min + ":" + t_sec);
function tempo2() {
var d2 = new Date();
var t_day2 = d2.getDate();
var t_hour2 = d2.getHours();
var t_min2 = d2.getMinutes();
var t_sec2 = d2.getSeconds();
var day = t_day2 - t_day;
var hour = t_hour2 - t_hour;
var min = t_min2 - t_min;
var sec = t_sec2 - t_sec;
document.getElementById('timespent').innerHTML = "Total--> '+day+'days, '+hour+':'+min+':'+sec";
}
setInterval(tempo2(), 500);
}
window.onload = tempo1();
</script>
<div id="timespent">??days, ??:??:??</div>
As a working axemple with a nice working algorithm:
<script>
startTime = new Date();
clockStart = startTime.getTime();
function initStopwatch() {
var NewTime = new Date();
return((NewTime.getTime() - clockStart)/1000);
}
function getSecs() {
var tSecs = Math.round(initStopwatch());
var iSecs = tSecs % 60;
var iMins = Math.round((tSecs-30)/60);
var sSecs ="" + ((iSecs > 9) ? iSecs : "0" + iSecs);
var sMins ="" + ((iMins > 9) ? iMins : "0" + iMins);
document.getElementById('timespent').innerHTML = sMins+":"+sSecs;
window.setTimeout(getSecs,1000);
}
window.onload=getSecs;
</script>
<div id=timespent></div>
On the line
…you’re calling the
tempo1function and assigning its return value to theloadevent onwindow. It’s exactly the same asx = foo();, wherefoogets called and the return value stored inx.You don’t want those
(), you just want:…which assigns the function reference, so it will get called when the
loadevent occurs.Similarly, as Graham points out, you’re doing the same sort of thing later:
which should be
There’s also a second error, on this line:
There, you’re quoting the string using double quotes (
"), but you’re using single quotes when trying to substitute in thedays,hour,min, andsecvariables. You need to be consistent about which quote you use to start and end a string. Either is fine, but you have to pick one, so either all doubles:or all singles:
Note that you don’t need to wait for the
loadevent, though. If you put your script at the bottom of the page (or anywhere below the “timespent”div— even immediately below it), you can just calltempo1directly. Theloadevent of thewindowobject happens very late in the page load cycle, after all external resources (including all images) are loaded. If that’s what you want, great, but if not you have an alternative.References: