有没有办法像 alert() 函数那样在 JavaScript 中强制同步行为?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14857118/
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-10-26 22:45:38  来源:igfitidea点击:

Is there a way to force synchronous behavior in JavaScript like the alert() function does?

javascriptjqueryasynchronous

提问by Maxx

When using alert or confirm in Javascript, the browser is forced into a synchronous process where everything (even the loading of another page) halts until the user dismisses the dialog.

当在 Javascript 中使用 alert 或 confirm 时,浏览器会被迫进入一个同步过程,在这个过程中,一切(甚至是另一个页面的加载)都会停止,直到用户关闭对话框。

I was wondering if there was any other way to force the browser to halt/pause using JS or jQuery.

我想知道是否还有其他方法可以使用 JS 或 jQuery 强制浏览器停止/暂停。

I looked at similar questions such as:

我查看了类似的问题,例如:

How to force javascript function execute synchronously/sequentially?

如何强制javascript函数同步/顺序执行?

How to make jQuery ui dialog box halt browser processing like an alert or confirmation box?

如何使 jQuery ui 对话框像警报或确认框一样停止浏览器处理?

Getting synchronous behavior in javascript?

在 javascript 中获取同步行为?

...but none of the answers seem to address the issue head on. If there is not a way to do it, I will fully accept that as an answer.

...但似乎没有一个答案能正面解决这个问题。如果没有办法做到这一点,我将完全接受它作为答案。

采纳答案by Aadit M Shah

No, there's currently no cross browser way to force an asynchronous function to execute synchronously.

不,目前没有跨浏览器的方式来强制异步函数同步执行。

However you may make use of continuations to write asynchronous code in a synchronous manner.

但是,您可以使用延续以同步方式编写异步代码。

Read the following answer for more details: https://stackoverflow.com/a/14809354/783743

阅读以下答案了解更多详情:https: //stackoverflow.com/a/14809354/783743