views:

23

answers:

1

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).

+1  A: 

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:

function yantra(){
    document.write("Hello<br>");
    i = 1;
    for(i = 0; i < 100; i++){
        setTimeout("writeOneNum()", 1000 * i);  
    }
}

By multiplying the time with i, the first is fired instantly, the second at 1000 * 1 = 1000 ms, the third at 1000 * 2 = 2000 ms etc.

In your case, it could be wiser to consider the setInterval function:

function yantra(){
    document.write("Hello<br>");
    setInterval("writeOneNum()", 1000);
}

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.

Tatu Ulmanen
So you're saying that JavaScript has a slight twist compared to Java code? What I'm getting is that, at certain level (In JavaScript) all the statements at a (theoretical level) are executed simultaneously compared to Java, where they're executed in sequence. So, did I get it right?
Catfish
The for loop itself will execute in less than one millisecond, and during that one millisecond, you are giving the command 'in 1000ms, execute this function' 100 times. setTimeout does not halt the execution of the for loop, it will continue the loop straight away. This should be similar in all languages, unless you are using some kind of sleep functionality.
Tatu Ulmanen