using setTimeout synchronously in JavaScript

Nathan picture Nathan · Nov 8, 2010 · Viewed 65k times · Source

I have the following scenario:

setTimeout("alert('this alert is timedout and should be the first');", 5000);
alert("this should be the second one");

I need the code after the setTimeout to be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeout is not code of my own I can't put it in the function called in the setTimeout...

Is there any way around this?

Answer

David Hedlund picture David Hedlund · Nov 8, 2010

Is the code contained in a function?

function test() {
    setTimeout(...);     

    // code that you cannot modify?
}

In that case, you could prevent the function from further execution, and then run it again:

function test(flag) {

    if(!flag) {

        setTimeout(function() {

           alert();
           test(true);

        }, 5000);

        return;

    }

    // code that you cannot modify

}