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?
No, as there is no delay function in Javascript, there is no way to do this other than busy waiting (which would lock up the browser).
I came in a situation where I needed a similar functionality last week and it made me think of this post. Basically I think the "Busy Waiting" to which @AndreKR refers, would be a suitable solution in a lot of situations. Below is the code I used to hog up the browser and force a wait condition.
Keep in mind that this code acutally holds up your browser. Hope it helps anyone.
Just put it inside the callback:
Is the code contained in a function?
In that case, you could prevent the function from further execution, and then run it again:
ES6 (busy waiting)
usage:
You could attempt to replace window.setTimeout with your own function, like so
Which may or may not work properly at all. Besides this, your only option would be to change the original code (which you said you couldn't do)
Bear in mind, changing native functions like this is not exactly a very optimal approach.