I am trying to run small snippet code in JavaScript, where I want to write on the web page simple hello world each 5 seconds. I think it must be ok, but no, still I got only first hello world and no more. Could you give me a hand in this? Thanks
<script type="text/javascript">
var i=0;
function startTimer() {
window.setTimeout('refresh()',5000);
}
function refresh() {
document.write("Hello world "+i+"<br/>");
i++;
window.setTimeout('startTimer()',1);
}
startTimer();
</script>
NOTE: As Amar Palsapure has noted in this answer, the root cause of the problem was the use of
document.write. In my demonstration, I use apelement todocument.body.appendChild()to add the text to the screen.You can use
setTimeout(), but you have to make it contingent on the lastsetTimeout()that ran; so that each time the caller runs, it creates the next timeout.setInterval()is designed to run at a “regular” interval (neithersetTimeout()norsetInterval()are truly reliable in when they run); however, if the calls tosetInterval()get backed up due to some other process blocking it’s execution (Javascript is single-threaded), you could have issues with those queued callbacks. That’s why I prefer the approach I have below.Note, refrain from the
setTimeout('funcCalled()', 100)usage; this is running aneval()on that string you’re passing in, which can change the scope in which you’re running the callback, as well as being considered “evil” due to security issues related toeval(). You’re best to avoid it altogether.EDIT – Modified slightly.
I have made some changes to the approach. See my comments.
http://jsfiddle.net/tXFrf/2/