在 JavaScript 中同步使用 setTimeout
我有以下场景:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
代码是否包含在函数中?
在这种情况下,您可以阻止该函数进一步执行,然后再次运行它:
Is the code contained in a function?
In that case, you could prevent the function from further execution, and then run it again:
上周我遇到了需要类似功能的情况,这让我想到了这篇文章。基本上我认为@AndreKR 提到的“忙等待”在很多情况下都是一个合适的解决方案。下面是我用来占用浏览器并强制等待条件的代码。
请记住,此代码实际上会阻止您的浏览器。
希望它对任何人都有帮助。
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.
使用 ES6 和承诺与承诺async 你可以实现同步运行。
那么代码在做什么呢?
Using ES6 & promises & async you can achieve running things synchronously.
So what is the code doing?
只需将其放入回调中即可:
Just put it inside the callback:
不可以,由于 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).
您可以创建一个承诺并等待其履行
You can create a promise and
await
for its fulfillmentES6(忙等待)
用法:
ES6 (busy waiting)
usage:
这是在代码中进行同步延迟的好方法:
在这里找到它 在 JavaScript 中同步延迟执行而不使用循环或超时的正确方法!
Here's a good way to make synchronous delay in your code:
Found it here Right way of delaying execution synchronously in JavaScript without using Loops or Timeouts!
我认为你必须做出承诺,然后使用 .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
您可以尝试用自己的函数替换 window.setTimeout ,就像这样,
这可能会或可能根本无法正常工作。除此之外,您唯一的选择是更改原始代码(您说您不能这样做)
请记住,像这样更改本机函数并不是一个非常理想的方法。
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.