I’m currently a beginner at JavaScript and predominantly code in Java.
My Question is is regarding invoking the document.write("string here") periodically (every 1/2 seconds) to append any new unprinted chat message to the client. I earlier tried using the following code :
<html>
<body onload="yantra();">
<script type="text/javascript">
x = 0;
function yantra(){
document.write("Hello<br>");
i = 1;
for(i = 0; i < 100; i++){
setTimeout("writeOneNum()", 1000);
}
}
function writeOneNum(){
x =x + 1;
document.write(x+"<br>");
}
function blank(){}
</script>
</body>
</html>
Instead of it printing 1 to 100 every 1000 millisecond as I expected it to print; in actuality, it printed 1 to 100 at one go (meaning without any delay).
Well, you are setting all the timeouts at once, so of course it fires them all at once. Your code will work with small modification to the loop:
By multiplying the time with
i, the first is fired instantly, the second at1000 * 1 = 1000ms, the third at1000 * 2 = 2000ms etc.In your case, it could be wiser to consider the setInterval function:
That will fire the
writeOneNum()every second infinitely. To stop the interval at some point, take a look at clearInterval on that same link above.