简体   繁体   English

在 JavaScript 中同步使用 setTimeout

[英]using setTimeout synchronously in JavaScript

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.我需要在执行setTimeout的代码后执行setTimeout之后的代码。 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...由于setTimeout之后的代码不是我自己的代码,我不能把它放在 setTimeout 中调用的函数中......

Is there any way around this?有没有办法解决?

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

}

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.基本上我认为@AndreKR 所指的“忙等待”在很多情况下都是合适的解决方案。 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.希望它可以帮助任何人。

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

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

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

ES6 (busy waiting) ES6(忙等待)

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

usage:用法:

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

I think you have to make a promise and then use a .then() so that you can chain your code together.我认为您必须做出承诺,然后使用 .then() 才能将代码链接在一起。 you should look at this articlehttps://developers.google.com/web/fundamentals/primers/promises你应该看看这篇文章https://developers.google.com/web/fundamentals/primers/promises

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.请记住,像这样更改本机函数并不是一种非常理想的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM