Catfish
Catfish

Reputation: 709

How to produce a time delay in JavaScript for a chat App?

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

Upvotes: 0

Views: 562

Answers (1)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124828

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.

Upvotes: 1

Related Questions