在 JavaScript 中同步使用 setTimeout

发布于 2024-10-01 02:36:39 字数 312 浏览 3 评论 0原文

我有以下场景:

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

我需要在执行setTimeout中的代码之后执行setTimeout之后的代码。由于 setTimeout 之后的代码不是我自己的代码,我无法将其放入 setTimeout 中调用的函数中...

有什么办法解决这个问题吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

等数载,海棠开 2024-10-08 02:36:39

代码是否包含在函数中?

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

    // code that you cannot modify?
}

在这种情况下,您可以阻止该函数进一步执行,然后再次运行它:

function test(flag) {

    if(!flag) {

        setTimeout(function() {

           alert();
           test(true);

        }, 5000);

        return;

    }

    // code that you cannot modify

}

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

}
妄想挽回 2024-10-08 02:36:39

上周我遇到了需要类似功能的情况,这让我想到了这篇文章。基本上我认为@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");

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

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.

黄昏下泛黄的笔记 2024-10-08 02:36:39

使用 ES6 和承诺与承诺async 你可以实现同步运行。

那么代码在做什么呢?

// 1. Calls setTimeout 1st inside of demo then put it into the webApi Stack
// 2. Creates a promise from the sleep function using 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();

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

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 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();
吃兔兔 2024-10-08 02:36:39

只需将其放入回调中即可:

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

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);
将军与妓 2024-10-08 02:36:39

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

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

2024-10-08 02:36:39

您可以创建一个承诺并等待其履行

const timeOut = (secs) => new Promise((res) => setTimeout(res, secs * 1000));

await timeOut(1000)

You can create a promise and await for its fulfillment

const timeOut = (secs) => new Promise((res) => setTimeout(res, secs * 1000));

await timeOut(1000)
ペ泪落弦音 2024-10-08 02:36:39

ES6(忙等待)

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

用法:

delay(1000)

ES6 (busy waiting)

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

usage:

delay(1000)
猛虎独行 2024-10-08 02:36:39

这是在代码中进行同步延迟的好方法:

async function yourFunction() {
  //your code
  await delay(n);
  //your code
}

function delay(n) {
  n = n || 2000;
  return new Promise(done => {
    setTimeout(() => {
      done();
    }, n);
  });
}

在这里找到它 在 JavaScript 中同步延迟执行而不使用循环或超时的正确方法!

Here's a good way to make synchronous delay in your code:

async function yourFunction() {
  //your code
  await delay(n);
  //your code
}

function delay(n) {
  n = n || 2000;
  return new Promise(done => {
    setTimeout(() => {
      done();
    }, n);
  });
}

Found it here Right way of delaying execution synchronously in JavaScript without using Loops or Timeouts!

猥琐帝 2024-10-08 02:36:39
setTimeout(function() {
  yourCode();    // alert('this alert is timedout and should be the first');
  otherCode();   // alert("this should be the second one");
}, 5000);
setTimeout(function() {
  yourCode();    // alert('this alert is timedout and should be the first');
  otherCode();   // alert("this should be the second one");
}, 5000);
红玫瑰 2024-10-08 02:36:39

我认为你必须做出承诺,然后使用 .then() ,以便你可以将你的代码链接在一起。你应该看看这篇文章 https://developers.google.com/web/fundamentals/底漆/承诺

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

不即不离 2024-10-08 02:36:39

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

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

这可能会或可能根本无法正常工作。除此之外,您唯一的选择是更改原始代码(您说您不能这样做)

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文