I want the browser to display the seconds since it was last refreshed. I don't understand why
Code 1 does not work;
Code 2 does;
If code 1 does not work why does code 3 work? The setInterval
call is similar in CODE 1 and CODE 3. The way the function is defined is different. But it is not clear to me why that is making a difference.
Thanks very much for your help. I have just started learning JavaScript.
CODE 1
<html>
<head>
<title>Time Since Refresh</title>
</head>
<body>
<br/>
<br/>
<span id="timeSinceStart"></span>
<script language="JavaScript">
var timeRefreshed = new Date();
function displayTimeSinceStart(){
var now = new Date();
//compute elapsed time
var elapsed = Math.round((now - timeRefreshed)/1000);
document.getElementById("timeSinceStart").innerHTML = "Time Elapsed: " + elapsed + " seconds.";
}
// Update seconds counter
setInterval(displayTimeSinceStart(), 1000);
</script>
</body>
</html>
CODE 2
Same as CODE 1, except the setInterval()
function is written as
setInterval("displayTimeSinceStart();", 1000);
CODE 3
<html>
<head>
<title>Time Since Refresh</title>
</head>
<body>
<br/>
<br/>
<span id="timeSinceStart"></span>
<script language="JavaScript">
var timeRefreshed = new Date();
var timeSinceStart = {
displayTimeSinceStart: function(){
var now = new Date();
//compute elapsed time
var elapsed = Math.round((now - timeRefreshed)/1000);
document.getElementById("timeSinceStart").innerHTML = "Time Elapsed: " + elapsed + " seconds.";
}
}
// Update seconds counter
setInterval(timeSinceStart.displayTimeSinceStart, 1000);
</script>
</body>
</html>