views:

660

answers:

3

Hello All,

I know at first glance (due to the title) this looks like one of the "Did you try searching Google before posting?" questions, but I can't seem to find an answer for the specific issue I'm experiencing. Sorry if I'm a noob.... still learning :)

I need to simulate a pause in javascript, but the setTimeout(function_call, timeout) function is not working for me. Reason being... when that setTimeout function is called, it then makes the function call asynchronously.

A little background:
I'm trying to simulate text being typed into a div at randomly timed intervals. I want it to appear as if a person is actually typing a message while the user is viewing the page. Since the timeout is a random interval and the function call is made asynchronously, the text ends up being printed in a random order.

Here is a snippet of what I have thus far:

typeString: function(s)
{
    for(var i=0;i<s.length;i++)
    {                      
        var c = s.charAt(i);
        var temp = setTimeout("MessageType.typeChar('" + c + "')", this.genRandomTime());
    }
}



Thanks in advance for your help.

CJAM



UPDATE: By adding the timer delay to a varialbe, it enabled me to offset timeOut for the asynchronous calls. Thank you all for your quick responses. Here is the updated code:

typeString: function(s)
{
    var delay = 0;

    for(var i=0;i<s.length;i++)
    {                     
        var c = s.charAt(i);
        setTimeout("GoogleTyper.typeChar('"+c+"')", delay += this.genRandomTime());
    }
}
+3  A: 

Have you tried cumulatively setting the timeout? Stick a variable outside of your loop and initialize it to 0. Let's call it timeout for now. Add a random amount of time to this variable at the beginning of each iteration of your loop, and make the timeout work off of that. This way, you are ensured that functions are being called in order.

Stuart Branham
+2  A: 

Your problem is you are using one all your times are delayed starting from now - the next timer needs to be fired after the previous. Simply add the previous timer delay to the new timer.

typeString: function(s)
{
    var delay = 0;
    for(var i=0;i<s.length;i++)
    {                      
        var c = s.charAt(i);
        delay = delay + this.genRandomTime();
        var temp = setTimeout("MessageType.typeChar('" + c + "')", delay );
    }
}
mP
I like your answer because it's very in depth, but I have to give the credit to Stuart B since he posted it before yours. The old fastest gun in the west routine :( Hopefully, other people will upvote you and earn you some points for being nice and helping out. Thanks you!!
regex
+1  A: 

Instead of passing to each timer event that character to be displayed, let each event handler grab the next character off of a queue (array, list whatever), so the order is maintained.

Assaf Lavie