如何终止 JavaScript 中的脚本?
如何像 PHP 的 exit
或 die
一样退出 JavaScript 脚本? 我知道这不是最好的编程实践,但我需要这样做。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何像 PHP 的 exit
或 die
一样退出 JavaScript 脚本? 我知道这不是最好的编程实践,但我需要这样做。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(26)
“exit”函数通常退出程序或脚本以及作为参数的错误消息。 例如 php 中的 die(...)
JS 中的等效方法是使用 throw 关键字发出错误信号,如下所示:
您可以轻松测试此:
"exit" functions usually quit the program or script along with an error message as paramete. For example die(...) in php
The equivalent in JS is to signal an error with the throw keyword like this:
You can easily test this:
PHP 的
die
的 JavaScript 等效项。 顺便说一句,它只是调用exit()
< /a> (感谢 splattne):JavaScript equivalent for PHP's
die
. BTW it just callsexit()
(thanks splattne):即使在没有句柄、事件等的简单程序中,最好将代码放在
main
函数中,即使它是唯一的过程:这样,当您想要停止程序时,您可以使用
返回
。Even in simple programs without handles, events and such, it is best to put code in a
main
function, even when it is the only procedure :This way, when you want to stop the program you can use
return
.有许多方法可以退出 JS 或 Node 脚本。 以下是最相关的:
如果您在 REPL 中(即运行
node 之后
在命令行上),您可以输入.exit
退出。There are many ways to exit a JS or Node script. Here are the most relevant:
If you're in the REPL (i.e. after running
node
on the command line), you can type.exit
to exit.如果您不在乎这是一个错误,只需编写:
这将阻止您的主(全局)代码继续进行。
对于调试/测试的某些方面很有用。
If you don't care that it's an error just write:
That will stop your main (global) code from proceeding.
Useful for some aspects of debugging/testing.
可以在开发工具中禁用 Javascript:
ctrl+shift+j
后跟cltf+shift+p
然后输入disable javascript
或f12 -> <代码>f1 -> 在调试器组中勾选
禁用JavaScript
已提到的可能选项:
处理超时、ajax、事件:
清除所有超时
中止DOM/XMLHttpRequest
删除所有事件监听器,包括内联
这将删除脚本并重新创建没有事件的元素
如果jQuery在网页上不可用复制粘贴源代码进入控制台。
可能还有其他东西。 请在评论中告诉我。
Javascript can be disabled in devtools:
ctrl+shift+j
followedcltf+shift+p
then typedisable javascript
orf12
->f1
-> tickDisable JavaScript
in Debugger groupPossible options that have been mentioned:
To deal with timeouts, ajax, events:
Clear all timeouts
abort DOM/XMLHttpRequest
remove all event listeners including inline
this removes scripts and recreates elements without events
If jQuery is not available on the webpage copy-paste source code into a console.
There're might be other stuff. Let me know in a comment.
将
debugger;
关键字放置在 JavaScript 代码中要停止执行的位置。 然后打开您最喜欢的浏览器的开发人员工具并重新加载页面。 现在它应该自动暂停。 打开工具的源部分:debugger;
关键字突出显示,您可以选择恢复脚本执行。我希望它有帮助。
更多信息请访问:
https://developer.mozilla .org/de/docs/Tools/Debugger
http: //www.w3schools.com/js/js_debugging.asp
Place the
debugger;
keyword in your JavaScript code where you want to stop the execution. Then open your favorite browser's developer tools and reload the page. Now it should pause automatically. Open the Sources section of your tools: thedebugger;
keyword is highlighted and you have the option to resume script execution.I hope it helps.
More information at:
https://developer.mozilla.org/de/docs/Tools/Debugger
http://www.w3schools.com/js/js_debugging.asp
JavaScript 中有多种方法,下面是其中的一些
方法 1:
方法 2:
方法 3:
方法 4:
方法5:
使用上述方法编写自定义函数并在需要的地方调用
注意:
如果您只想暂停代码执行,可以使用
In JavaScript multiple ways are there, below are some of them
Method 1:
Method 2:
Method 3:
Method 4:
Method 5:
write your custom function use above method and call where you needed
Note:
If you want to just pause the code execution you can use
就我而言,我使用了
window.stop
。In my case I used
window.stop
.我认为这个问题已经得到解答,请点击此处了解更多信息。 以下是发布的简短答案。
您还可以使用浏览器添加断点,每个浏览器都是相似的,请检查下面适合您的浏览器的信息。
有关 Chrome 断点信息,请点击此处
有关 Firefox 断点信息,请点击此处
有关资源管理器断点信息单击
有关 Safari 断点信息,请点击此处
I think this question has been answered, click here for more information. Below is the short answer it is posted.
You can also used your browser to add break points, every browser is similar, check info below for your browser.
For Chrome break points info click here
For Firefox break points info click here
For Explorer break points info click
For Safari break points info click here
如果您只是想阻止进一步的代码执行而不“抛出”任何错误,您可以暂时覆盖
window.onerror
,如交叉退出
:If you just want to stop further code from executing without "throwing" any error, you can temporarily override
window.onerror
as shown incross-exit
:扔 ””;
这是对概念的误用,但可能是唯一的选择。 而且,是的,您将必须重置所有事件侦听器,就像接受的答案提到的那样。 如果我是对的,您还需要一个单一的入口点。
最重要的是:您想要一个在抛出时立即通过电子邮件向您报告的页面 - 您可以使用例如 Raven/Sentry 来实现此目的。 但这意味着,你会给自己带来误报。 在这种情况下,您还需要更新默认处理程序以过滤掉此类事件或在 Sentry 仪表板上设置忽略此类事件。
窗口.stop();
这在页面加载期间不起作用。 它还会停止页面的解码。 因此,您不能真正使用它为用户提供页面的无 JavaScript 变体。
调试器;
仅在调试器打开时停止执行。 效果很好,但不是可交付成果。
throw "";
Is a misuse of the concept but probably the only option. And, yes, you will have to reset all event listeners, just like the accepted answer mentions. You would also need a single point of entry if I am right.
On the top of it: You want a page which reports to you by email as soon as it throws - you can use for example Raven/Sentry for this. But that means, you produce yourself false positives. In such case, you also need to update the default handler to filter such events out or set such events on ignore on Sentry's dashboard.
window.stop();
This does not work during the loading of the page. It stops decoding of the page as well. So you cannot really use it to offer user a javascript-free variant of your page.
debugger;
Stops execution only with debugger opened. Works great, but not a deliverable.
如果您正在寻找一种方法来强制终止页面上所有 JavaScript 的执行,我不确定是否有官方认可的方法来做到这一点 - 这似乎是一种可能存在安全风险的事情(尽管对于老实说,我无法想象它会如何从我的脑海中消失)。 通常在 Javascript 中,当您希望代码停止运行时,您只需从正在执行的任何函数中
返回
即可。 (如果return
语句是函数中的最后一件事并且函数不应返回值,则它是可选的)如果由于某种原因返回对您来说不够好,您可能应该编辑更多详细信息询问为什么你认为你需要它,也许有人可以提供替代解决方案。请注意,实际上,大多数浏览器的 Javascript 解释器在遇到错误时都会停止运行当前脚本。 因此,您可以执行类似访问未设置变量的属性之类的操作:
它可能会中止脚本。 但你不应该指望这一点,因为它根本不标准,而且看起来确实是一种糟糕的做法。
编辑:好吧,根据 Ólafur 的观点,也许这不是一个好的答案。 尽管他链接到的die()函数基本上实现了我的第二段,即它只是抛出一个错误。
If you're looking for a way to forcibly terminate execution of all Javascript on a page, I'm not sure there is an officially sanctioned way to do that - it seems like the kind of thing that might be a security risk (although to be honest, I can't think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just
return
from whatever function is executing. (Thereturn
statement is optional if it's the last thing in the function and the function shouldn't return a value) If there's some reason returning isn't good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.Note that in practice, most browsers' Javascript interpreters will simply stop running the current script if they encounter an error. So you can do something like accessing an attribute of an unset variable:
and it will probably abort the script. But you shouldn't count on that because it's not at all standard, and it really seems like a terrible practice.
EDIT: OK, maybe this wasn't such a good answer in light of Ólafur's. Although the
die()
function he linked to basically implements my second paragraph, i.e. it just throws an error.要停止脚本执行而不出现任何错误,您可以将所有脚本包含到一个函数中并执行它。
这是一个例子:
上面的脚本只会记录一个。
使用之前
To stop script execution without any error, you can include all your script into a function and execute it.
Here is an example:
The script above will only log one.
Before use
这个小函数非常接近于模仿 PHP 的 exit()。 与其他解决方案一样,不要添加任何其他内容。
This little function comes pretty close to mimicking PHP's exit(). As with the other solutions, don't add anything else.
如果您在脚本中使用任何未定义的函数,则脚本将因“未捕获的引用错误”而停止。 我尝试过以下代码并执行前两行。
我认为,这是停止脚本的最好方法。 如果还有其他方法请评论我。 我还想知道另一种最好且简单的方法。 顺便说一句,我没有像 PHP 那样在 Javascript 中获得 exit 或 die 内置函数来终止脚本。 如果有人知道请告诉我。
If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.
I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or die inbuilt function in Javascript like PHP for terminate the script. If anyone know then please let me know.
我知道这已经很旧了,但是如果您想要一个类似的 PHP
die()
函数,您可以这样做:用法:
上面的示例只会打印“Hello”。
I know this is old, but if you want a similar PHP
die()
function, you could do:Usage:
The example above will only print "Hello".
用函数包装
Wrapp with a function
简而言之:不,没有方法可以使用与 PHP 的
exit
或die()
(顺便说一句,还有几乎所有其他编程语言)。由于OP没有指定他们试图停止执行的位置,因此人们不应该假设他们意味着“在浏览器中”或“在Node.js中”或甚至“在某些嵌入 ECMAScript 虚拟机和/或解释器的应用程序中”或者,谁知道呢,纯本机编译的 JavaScript使用书呆子。 假设其中任何一个自然是OP的可能环境,一个完整答案应该尝试涵盖所有这些,并且,如果可能的话,甚至考虑未来的建议。
因此,从已经给出的大量答案中,我只指出其中的几个; 大多数答案都是这些答案的变体,带有或多或少的铃声和提示。 口哨声,可能还有更详细的解释。
函数式方法
这本质上是将您的代码包装在函数周围,然后仅使用
return
退出该函数; 没有更多的事情了。最简单的示例是使用匿名函数,如@bellisario的答案所建议:
对于浏览器环境,您可能需要添加该函数作为页面加载时启动的事件。 其他环境可能甚至不需要它。 或者,您可以将其设为命名函数并显式调用它,无论您喜欢什么(将其称为
main()
会很有意义,因为它与C 中的其他编程语言保持一致)
家庭)。优点:它可以在任何环境下工作。 在“标准”方面你无法击败它。 不会向控制台抛出或记录任何错误(除非您想要明确地这样做)。
缺点:请参阅@bellisario 指出的警告。
显式抛出错误
优点:应该普遍可用。 还应该做任何需要清理的事情。
缺点:正如它所说,它抛出一个错误,可以说,这不是“干净的退出”。 虽然错误消息可以为空,但大多数 JS 环境仍然会将其视为错误并相应地对其进行标记。 当需要“干净”退出时(因为没有进一步的处理要做),但用户看到意外的“错误”(即使消息只是“这不是错误;脚本已成功终止”),这可能特别烦人!”)。
使用无效的东西隐式地强制错误
除了“失败”之外,您实际上可以使用代码中不存在的任何东西,甚至是类似的东西,您知道...
exit
或死亡
。优点:代码不会显示错误,因此程序员阅读代码时不会思考< /em> 将构造视为“错误”。
缺点:一切!
的东西失败
或退出
或死亡
或任何被选择导致错误的东西,这会给程序员带来不可预测的结果(谁期望执行中止,而不是使用他们不知道之前已经定义的函数带来的一些未知的副作用)。 诚然,人们可能总是将自己的无效构造重命名为其他名称,但不能保证将来同样的情况不会再次发生!因此,很可能,这是第二个最糟糕的可能方法(我在这里看到的最糟糕的方法是建议无限循环以避免进一步的代码执行......)。
浏览器环境之外的 JavaScript
同样,那里没有通用标准; 但由于很可能大多数浏览器外的JavaScript正在Node.js下运行,@not2qbit的答案 应该可以解决问题:
优点:这与
C
系列编程语言下进程(干净地)退出的方式最相似,因此是一个熟悉的习惯用法。缺点:当然,它只能在 Node.js 下工作。 每个实现都有不同的终止进程的方式(例如,Deno 使用 Deno.exit ())。 当然,这可能也会在基于浏览器的 JavaScript 上引发错误(由于
process
是一个不存在的对象),从而强制脚本因错误而中止,但是,如前所述,这并不是解决问题的最佳方法。In short: no, there is no way to exit/kill/terminate a running with the same semantics as implied by PHP's
exit
ordie()
(and, incidentally, almost all other programming languages out there).Since the OP didn't specify where they're attempting to stop execution, one should not assume that they meant "in a browser" or "in Node.js" or even "in some application that embeds an ECMAScript virtual machine and/or interpreter" or, who knows, pure natively-compiled JavaScript using Nerd. Assuming either of those is naturally a possible environment for the OP, a full answer should attempt to encompass them all, and, if possible, even take into account future suggestions.
From the plethora of answers already given, I therefore point out to just a few; most answers will be a variant of those, with more or less bells & whistles, and possibly more detailed explanations.
Functional approach
This is essentially wrapping your code around a function and just use
return
to exit the function; there is nothing more to it.The easiest example is by using an anonymous function, as suggested by @bellisario's answer:
For browser environments, you might need to add this function as an event that gets launched when a page loads. Other environments might not even need that. Or you can make it a named function instead and call it explicitly, whatever you prefer (calling it
main()
would make a lot of sense due to its consistency with other programming languages in theC
family).Pros: It works under any environment. You cannot beat it in terms of "standard". No errors are thrown or logged to the console (unless you want to, doing it explicitly).
Cons: See the caveats pointed out by @bellisario.
Explicitly throwing an error
Pros: Should be universally available. Should also do whatever cleaning up is required.
Cons: As it says, it throws an error, which is not a "clean exit", so to speak. While the error message can be empty, most JS environments will still see it as an error and flag it accordingly. This might be especially annoying when a "clean" exit is required (because there is no further processing to do) but the user sees an unexpected "error" (even if the message is simply "this isn't an error; script terminated successfully!").
Implicitly forcing an error using something invalid
Instead of "fail" you can essentially use anything which doesn't exist in your code, even something like, you know...
exit
ordie
.Pros: The code does not show an error, so programmers reading the code will not think of the construct as an "error".
Cons: Everything!
fail
orexit
ordie
or whatever was picked to cause the error, and this will give unpredictable results to the programmer (who is expecting execution to abort, not some unknown side-effects from using a function that they didn't know that had already been defined before). Granted, one may always rename one's invalid construct to something else, but it's not guaranteed that in the future the same won't happen again!throw new Error(...)
— which is syntactically correct, even if semantically it might give the wrong notion (mathematically speaking, the absence of an error is also an error in itself; the "null error" if you wish, i.e. the error that is not part of the set of possible errors; however, such philosophical considerations are beyond the scope of this discussion) — each and every programmer will use a different invalid construct to break away from code (just look at the above answers, all of them using the same technique, but somehow those writing the answers seem unaware that they're all variants of the same concept...), which will make code written by different programmers next-to-impossible to maintain.So, very likely, this is the second worst possible approach (the worst I saw posted here was suggesting an infinite loop to avoid further code execution...).
JavaScript outside of the browser environment
Again, there is no universal standard there; but since it's likely that most JavaScript-out-of-the-browser is being run under Node.js, @not2qbit's answer should do the trick:
Pros: This most closely resembles the way processes are (cleanly) exited under the
C
family of programming languages, and is therefore a familiar idiom.Cons: Of course, it will only work under Node.js. Each implementation will have different ways of terminating the process (Deno, for instance, uses Deno.exit()). Granted, possibly this might throw an error on browser-based JavaScript as well (due to
process
being an inexistent object) and thus force the script to abort with an error, but, as mentioned before, that's hardly the best way to deal with it.我使用这段代码来停止执行:
虽然您会收到控制台错误,但它对我很有用。
i use this piece of code to stop execution:
you will get a console error though but it works good for me.
我正在使用 iobroker 并轻松地停止脚本
I am using iobroker and easily managed to stop the script with
这是一个例子,
如果存在条件,则终止脚本。
我在我的 SSE 客户端 javascript 中使用它,如果
无法从 JSON 解析中正确解析......
无论如何,总体思路是:
这将终止/终止你的 javasript 脚本
This is an example, that,
if a condition exist, then terminate the script.
I use this in my SSE client side javascript, if the
canot be parsed right from JSON parse ...
... anyway the general idea is:
this will terminate/die your javasript script
只需创建一个 BOOL 条件,
这里不需要复杂的代码..
即使一次将其设置为 true/或多次,
它都会给你一行解决方案/而不是多个 -
基本上就这么简单。
Simply create a BOOL condition ,
no need for complicated code here..
If even once you turn it to true/ or multiple times,
it will both give you one line of solution/not multiple -
basically simple as that.
在大多数情况下不适用,但我在浏览器中运行了很多异步脚本,并且作为一种黑客手段,我
阻止了一切。
Not applicable in most circumstances, but I had lots of async scripts running in the browser and as a hack I do
to stop everything.
此代码将停止当前窗口中所有 JavaScript 的执行:
示例
This code will stop execution of all JavaScripts in current window:
Example
我使用 return 语句而不是 throw ,因为 throw 在控制台中给出错误。 最好的方法是检查条件,
这只是停止该行程序的执行,而不是在控制台中给出任何错误。
i use return statement instead of throw as throw gives error in console. the best way to do it is to check the condition
this simply stops the execution of the program from that line, instead of giving any errors in the console.