The following code is from ‘JavaScript by Example Second Edition’,I think the code below is better
function scroller() {
str = str.substring(1, str.length) + str.substring(0, 1);
document.title = str;
window.status = str;
}
setInterval(scroller, 300);
The old code is recursive and will continue to call itself every 0.3 seconds until the program ends, I think the old code maybe cause stack overflow, right?
<html>
<!-- This script is a modification of a free script found at
the JavaScript source.
Author: Asif Nasir (Asifnasir@yahoo.com)
-->
<head>
<script type="text/javascript">
var today = new Date();
var year = today.getFullYear();
var future = new Date("December 25, " + year);
var diff = future.getTime() - today.getTime();
// Number of milliseconds
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
// Convert to days
var str =
"Only " + days + " shopping days left until Christmas!";
function scroller() {
str = str.substring(1, str.length) + str.substring(0, 1);
document.title = str;
window.status = str;
setTimeout(scroller, 300); // Set the timer
}
</script>
</head>
<body onload="scroller()">
<b>
<font color="green" size="4">
Get Dizzy. Watch the title bar and the status bar!!
<br />
<image src="christmasscene.bmp">
</font>
</body>
</html>
setIntervalis good if you don’t care too much about accuracy, e.g. polling for some condition to be met.setTimeoutis good if you want a one–off event or need to adjust the interval between calls, e.g. a clock that should update as close as possible to just after the next whole second.Both can be used for events that run continuously at approximately the specified interval, both can be cancelled, both only run at about (as soon as possible after) the designated time interval.
Incidentally, the first code example in the OP should not cause a stack overflow, though it is otherwise not very well written.