在 JavaScript 中同步使用 setTimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4122268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:00:48  来源:igfitidea点击:

using setTimeout synchronously in JavaScript

javascriptsettimeout

提问by Nathan

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 setTimeoutto be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeoutis not code of my own I can't put it in the function called in the setTimeout...

我需要在setTimeout执行 setTimeout 中的代码之后执行的代码。由于后面的setTimeout代码不是我自己的代码,我不能把它放在 setTimeout 中调用的函数中......

Is there any way around this?

有没有办法解决?

回答by dxh

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

}

回答by Nathan

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.

上周我遇到了需要类似功能的情况,这让我想到了这篇文章。基本上我认为@AndreKR 所指的“忙等待”在很多情况下都是合适的解决方案。下面是我用来占用浏览器并强制等待条件的代码。

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.

请记住,此代码实际上会阻止您的浏览器。希望它可以帮助任何人。

回答by Darin Dimitrov

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

回答by AndreKR

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

不,由于 Javascript 中没有延迟功能,因此除了忙等待(这会锁定浏览器)之外没有其他方法可以做到这一点。

回答by Andrey

ES6 (busy waiting)

ES6(忙等待)

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

usage:

用法:

delay(1000)

回答by РАВИ

Using ES6 & promises & async you can achieve running things synchronously.

使用 ES6 & promises & async 你可以实现同步运行。

So what is the code doing?

那么代码在做什么呢?

 1. Calls setTimeOut 1st inside of demo then put it into the webApi Stack
 2. Creates a promise from the sleep function using the setTimeout, then resolves after the timeout has been completed;
 3. By then, the first setTimeout will reach its timer and execute from webApi stack. 
 4. Then following, the remaining alert will show up.


function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  setTimeout("alert('this alert is timedout and should be the first');", 5000);
  await sleep(5000);
  alert('this should be the second one');
}
demo();

回答by Marcel Hymanwerth

setTimeout(function() {
  yourCode();    // alert('this alert is timedout and should be the first');
  otherCode();   // alert("this should be the second one");
}, 5000);

回答by Jani Hartikainen

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

你可以尝试用你自己的函数替换 window.setTimeout,就像这样

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.

请记住,像这样更改本机函数并不是一种非常理想的方法。

回答by akili Sosa

I think you have to make a promise and then use a .then() so that you can chain your code together. you should look at this article https://developers.google.com/web/fundamentals/primers/promises

我认为您必须做出承诺,然后使用 .then() 才能将代码链接在一起。你应该看看这篇文章https://developers.google.com/web/fundamentals/primers/promises