using setTimeout synchronously in JavaScript

2019-01-16 12:09发布

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?

8条回答
仙女界的扛把子
2楼-- · 2019-01-16 12:43

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

查看更多
Viruses.
3楼-- · 2019-01-16 12:45

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.

function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

document.write("first statement");
alert("first statement");

pause(3000);

document.write("<br />3 seconds");
alert("paused for 3 seconds");

Keep in mind that this code acutally holds up your browser. Hope it helps anyone.

查看更多
Root(大扎)
4楼-- · 2019-01-16 12:48

Just put it inside the callback:

setTimeout(function() {
    alert('this alert is timedout and should be the first');
    alert('this should be the second one');
}, 5000);
查看更多
Bombasti
5楼-- · 2019-01-16 12:57

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

}
查看更多
老娘就宠你
6楼-- · 2019-01-16 12:57

ES6 (busy waiting)

const delay = (ms) => {
  const startPoint = new Date().getTime()
  while (new Date().getTime() - startPoint <= ms) {/* wait */}
}

usage:

delay(1000)
查看更多
趁早两清
7楼-- · 2019-01-16 13:04

You could attempt to replace window.setTimeout with your own function, like so

window.setTimeout = function(func, timeout) {
    func();
}

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.

查看更多
登录 后发表回答