如何终止 JavaScript 中的脚本?

发布于 2024-07-13 20:42:04 字数 97 浏览 6 评论 0 原文

如何像 PHP 的 exitdie 一样退出 JavaScript 脚本? 我知道这不是最好的编程实践,但我需要这样做。

How can I exit the JavaScript script much like PHP's exit or die? I know it's not the best programming practice but I need to.

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

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

发布评论

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

评论(26

装迷糊 2024-07-20 20:42:04

“exit”函数通常退出程序或脚本以及作为参数的错误消息。 例如 php 中的 die(...)

die("sorry my fault, didn't mean to but now I am in byte nirvana")

JS 中的等效方法是使用 throw 关键字发出错误信号,如下所示:

throw new Error();

您可以轻松测试此:

var m = 100;
throw '';
var x = 100;

x
>>>undefined
m
>>>100

"exit" functions usually quit the program or script along with an error message as paramete. For example die(...) in php

die("sorry my fault, didn't mean to but now I am in byte nirvana")

The equivalent in JS is to signal an error with the throw keyword like this:

throw new Error();

You can easily test this:

var m = 100;
throw '';
var x = 100;

x
>>>undefined
m
>>>100
随梦而飞# 2024-07-20 20:42:04

PHP 的 die 的 JavaScript 等效项。 顺便说一句,它只是调用 exit()< /a> (感谢 splattne):

function exit( status ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
    // +   improved by: Philip Peterson
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null

    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];

    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
    }

    if (window.stop) {
        window.stop();
    }

    throw '';
}

JavaScript equivalent for PHP's die. BTW it just calls exit() (thanks splattne):

function exit( status ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
    // +   improved by: Philip Peterson
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null

    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];

    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
    }

    if (window.stop) {
        window.stop();
    }

    throw '';
}
唔猫 2024-07-20 20:42:04

即使在没有句柄、事件等的简单程序中,最好将代码放在 main 函数中,即使它是唯一的过程:

<script> 
function main()
{
//code

}
main();
</script>

这样,当您想要停止程序时,您可以使用返回

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 :

<script> 
function main()
{
//code

}
main();
</script>

This way, when you want to stop the program you can use return.

倒数 2024-07-20 20:42:04

许多方法可以退出 JS 或 Node 脚本。 以下是最相关的:

// This will never exit!
setInterval((function() {  
    return;
}), 5000);

// This will exit after 5 seconds, with signal 1
setTimeout((function() {  
    return process.exit(1);
}), 5000);

// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {  
    return process.kill(process.pid);
}), 5000);

// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {  
    return process.abort();
}), 5000);

如果您在 REPL 中(即运行 node 之后 在命令行上),您可以输入 .exit 退出。

There are many ways to exit a JS or Node script. Here are the most relevant:

// This will never exit!
setInterval((function() {  
    return;
}), 5000);

// This will exit after 5 seconds, with signal 1
setTimeout((function() {  
    return process.exit(1);
}), 5000);

// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {  
    return process.kill(process.pid);
}), 5000);

// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {  
    return process.abort();
}), 5000);

If you're in the REPL (i.e. after running node on the command line), you can type .exit to exit.

半衬遮猫 2024-07-20 20:42:04

如果您不在乎这是一个错误,只需编写:

fail;

这将阻止您的主(全局)代码继续进行。
对于调试/测试的某些方面很有用。

If you don't care that it's an error just write:

fail;

That will stop your main (global) code from proceeding.
Useful for some aspects of debugging/testing.

装迷糊 2024-07-20 20:42:04

可以在开发工具中禁用 Javascript:ctrl+shift+j 后跟 cltf+shift+p 然后输入 disable javascriptf12 -> <代码>f1 -> 在调试器组中勾选禁用JavaScript

已提到的可能选项:

debugger; // debugs js as soon as entered
window.stop(); // equivalent to the 'stop' button in the browser
throw new Error(); // throws error
window.location.reload(); // reloads current page
for(;;); // crashes your browser

处理超时、ajax、事件:

清除所有超时

var id = window.setTimeout(function() {}, 0);
while (id--) {
    window.clearTimeout(id);
}

中止DOM/XMLHttpRequest

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(i, jqXHR) { 
        jqXHR.abort();  
        $.xhrPool.splice(i, 1); 
    });
}
$.ajaxSetup({
    beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR);
        if (i > -1) $.xhrPool.splice(i, 1); 
    }
});

删除所有事件监听器,包括内联

$("*").prop("onclick", null).off();

这将删除脚本并重新创建没有事件的元素

$('script').remove();
$('*').each(function(){
    $(this).replaceWith($(this).clone());   
});

如果jQuery在网页上不可用复制粘贴源代码进入控制台。

可能还有其他东西。 请在评论中告诉我。

Javascript can be disabled in devtools: ctrl+shift+j followed cltf+shift+p then type disable javascript or f12 ->f1 -> tick Disable JavaScript in Debugger group

Possible options that have been mentioned:

debugger; // debugs js as soon as entered
window.stop(); // equivalent to the 'stop' button in the browser
throw new Error(); // throws error
window.location.reload(); // reloads current page
for(;;); // crashes your browser

To deal with timeouts, ajax, events:

Clear all timeouts

var id = window.setTimeout(function() {}, 0);
while (id--) {
    window.clearTimeout(id);
}

abort DOM/XMLHttpRequest

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(i, jqXHR) { 
        jqXHR.abort();  
        $.xhrPool.splice(i, 1); 
    });
}
$.ajaxSetup({
    beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR);
        if (i > -1) $.xhrPool.splice(i, 1); 
    }
});

remove all event listeners including inline

$("*").prop("onclick", null).off();

this removes scripts and recreates elements without events

$('script').remove();
$('*').each(function(){
    $(this).replaceWith($(this).clone());   
});

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.

╰ゝ天使的微笑 2024-07-20 20:42:04

debugger; 关键字放置在 JavaScript 代码中要停止执行的位置。 然后打开您最喜欢的浏览器的开发人员工具并重新加载页面。 现在它应该自动暂停。 打开工具的部分:debugger; 关键字突出显示,您可以选择恢复脚本执行。

我希望它有帮助。

更多信息请访问:

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: the debugger; keyword is highlighted and you have the option to resume script execution.

I hope it helps.

More information at:

浮云落日 2024-07-20 20:42:04

JavaScript 中有多种方法,下面是其中的一些

方法 1:

throw new Error("Something went badly wrong!");

方法 2:

return;

方法 3:

return false;

方法 4:

new new

方法5:

使用上述方法编写自定义函数并在需要的地方调用

注意:
如果您只想暂停代码执行,可以使用

debugger; 

In JavaScript multiple ways are there, below are some of them

Method 1:

throw new Error("Something went badly wrong!");

Method 2:

return;

Method 3:

return false;

Method 4:

new new

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

debugger; 
夜清冷一曲。 2024-07-20 20:42:04

就我而言,我使用了 window.stop

window.stop() 会停止当前浏览上下文中的进一步资源加载,相当于浏览器中的“停止”按钮。

由于脚本的执行方式,此方法无法中断其父文档的加载,但会停止其图像、新窗口和其他仍在加载的对象。

用法 window.stop();
(来源)

In my case I used window.stop.

The window.stop() stops further resource loading in the current browsing context, equivalent to the 'stop' button in the browser.

Because of how scripts are executed, this method cannot interrupt its parent document's loading, but it will stop its images, new windows, and other still-loading objects.

Usage: window.stop();
(source)

冷默言语 2024-07-20 20:42:04

我认为这个问题已经得到解答,请点击此处了解更多信息。 以下是发布的简短答案。

throw new Error("Stop script");

您还可以使用浏览器添加断点,每个浏览器都是相似的,请检查下面适合您的浏览器的信息。

有关 Chrome 断点信息,请点击此处
有关 Firefox 断点信息,请点击此处
有关资源管理器断点信息单击
有关 Safari 断点信息,请点击此处

I think this question has been answered, click here for more information. Below is the short answer it is posted.

throw new Error("Stop script");

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

红墙和绿瓦 2024-07-20 20:42:04

如果您只是想阻止进一步的代码执行而不“抛出”任何错误,您可以暂时覆盖 window.onerror,如 交叉退出

function exit(code) {
    const prevOnError = window.onerror
    window.onerror = () => {
        window.onerror = prevOnError
        return true
    }

    throw new Error(`Script termination with code ${code || 0}.`)
}

console.log("This message is logged.");
exit();
console.log("This message isn't logged.");

If you just want to stop further code from executing without "throwing" any error, you can temporarily override window.onerror as shown in cross-exit:

function exit(code) {
    const prevOnError = window.onerror
    window.onerror = () => {
        window.onerror = prevOnError
        return true
    }

    throw new Error(`Script termination with code ${code || 0}.`)
}

console.log("This message is logged.");
exit();
console.log("This message isn't logged.");
海之角 2024-07-20 20:42:04

扔 ””;

这是对概念的误用,但可能是唯一的选择。 而且,是的,您将必须重置所有事件侦听器,就像接受的答案提到的那样。 如果我是对的,您还需要一个单一的入口点。

最重要的是:您想要一个在抛出时立即通过电子邮件向您报告的页面 - 您可以使用例如 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.

溺孤伤于心 2024-07-20 20:42:04

如果您正在寻找一种方法来强制终止页面上所有 JavaScript 的执行,我不确定是否有官方认可的方法来做到这一点 - 这似乎是一种可能存在安全风险的事情(尽管对于老实说,我无法想象它会如何从我的脑海中消失)。 通常在 Javascript 中,当您希望代码停止运行时,您只需从正在执行的任何函数中返回即可。 (如果 return 语句是函数中的最后一件事并且函数不应返回值,则它是可选的)如果由于某种原因返回对您来说不够好,您可能应该编辑更多详细信息询问为什么你认为你需要它,也许有人可以提供替代解决方案。

请注意,实际上,大多数浏览器的 Javascript 解释器在遇到错误时都会停止运行当前脚本。 因此,您可以执行类似访问未设置变量的属性之类的操作:

function exit() {
    p.blah();
}

可能会中止脚本。 但你不应该指望这一点,因为它根本不标准,而且看起来确实是一种糟糕的做法。

编辑:好吧,根据 Ó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. (The return 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:

function exit() {
    p.blah();
}

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.

幸福丶如此 2024-07-20 20:42:04

要停止脚本执行而不出现任何错误,您可以将所有脚本包含到一个函数中并执行它。
这是一个例子:

(function () {
    console.log('one');
    return;
    console.log('two');
})();

上面的脚本只会记录一个

使用之前

  • 如果您需要在脚本本身之外读取脚本的函数,请记住(通常)它不起作用:为此,您需要使用预先存在的变量或对象(您可以将函数放在 window 对象中)。
  • 上面的代码可能是您不想要的:将整个脚本放入函数中可能会产生其他后果(例如,这样做,脚本将立即运行,并且在开发过程中无法从浏览器修改其部分,据我所知,在 Chrome 中)

To stop script execution without any error, you can include all your script into a function and execute it.
Here is an example:

(function () {
    console.log('one');
    return;
    console.log('two');
})();

The script above will only log one.

Before use

  • If you need to read a function of your script outside of the script itself, remember that (normally) it doesn't work: to do it, you need to use a pre-existing variable or object (you can put your function in the window object).
  • The above code could be what you don't want: put an entire script in a function can have other consequences (ex. doing this, the script will run immediately and there isn't a way to modify its parts from the browser in developing, as I know, in Chrome)
無處可尋 2024-07-20 20:42:04

这个小函数非常接近于模仿 PHP 的 exit()。 与其他解决方案一样,不要添加任何其他内容。

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit

This little function comes pretty close to mimicking PHP's exit(). As with the other solutions, don't add anything else.

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit
撑一把青伞 2024-07-20 20:42:04

如果您在脚本中使用任何未定义的函数,则脚本将因“未捕获的引用错误”而停止。 我尝试过以下代码并执行前两行。

我认为,这是停止脚本的最好方法。 如果还有其他方法请评论我。 我还想知道另一种最好且简单的方法。 顺便说一句,我没有像 PHP 那样在 Javascript 中获得 exit 或 die 内置函数来终止脚本。 如果有人知道请告诉我。

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');

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.

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');
初与友歌 2024-07-20 20:42:04

我知道这已经很旧了,但是如果您想要一个类似的 PHP die() 函数,您可以这样做:

function die(reason) {
    throw new Error(reason);
}

用法:

console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");

上面的示例只会打印“Hello”。

I know this is old, but if you want a similar PHP die() function, you could do:

function die(reason) {
    throw new Error(reason);
}

Usage:

console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");

The example above will only print "Hello".

望笑 2024-07-20 20:42:04

用函数包装

(function(){
alert('start')

return;
alert('no exec')
})

Wrapp with a function

(function(){
alert('start')

return;
alert('no exec')
})
请帮我爱他 2024-07-20 20:42:04

简而言之:没有方法可以使用与 PHP 的 exitdie() (顺便说一句,还有几乎所有其他编程语言)。

由于OP没有指定他们试图停止执行的位置,因此人们不应该假设他们意味着“在浏览器中”或“在Node.js中”或甚至“在某些嵌入 ECMAScript 虚拟机和/或解释器的应用程序中”或者,谁知道呢,纯本机编译的 JavaScript使用书呆子假设其中任何一个自然是OP的可能环境,一个完整答案应该尝试涵盖所有这些,并且,如果可能的话,甚至考虑未来的建议。

因此,从已经给出的大量答案中,我只指出其中的几个; 大多数答案都是这些答案的变体,带有或多或少的铃声和提示。 口哨声,可能还有更详细的解释。

函数式方法

这本质上是将您的代码包装在函数周围,然后仅使用 return 退出该函数; 没有更多的事情了。

最简单的示例是使用匿名函数,如@bellisario的答案所建议:

(function () {
    console.log('this code gets executed');
    return;
    console.log('this code is never reached');
})();

对于浏览器环境,您可能需要添加该函数作为页面加载时启动的事件。 其他环境可能甚至不需要它。 或者,您可以将其设为命名函数并显式调用它,无论您喜欢什么(将其称为 main() 会很有意义,因为它与 C 中的其他编程语言保持一致) 家庭)。

优点:它可以在任何环境下工作。 在“标准”方面你无法击败它。 不会向控制台抛出或记录任何错误(除非您想要明确地这样做)。
缺点:请参阅@bellisario 指出的警告。

显式抛出错误

console.log('this code gets executed');
throw new Error("<write here some reason for exiting>");
console.log('this code is never reached');

优点:应该普遍可用。 还应该做任何需要清理的事情。
缺点:正如它所说,它抛出一个错误,可以说,这不是“干净的退出”。 虽然错误消息可以为空,但大多数 JS 环境仍然会将其视为错误并相应地对其进行标记。 当需要“干净”退出时(因为没有进一步的处理要做),但用户看到意外的“错误”(即使消息只是“这不是错误;脚本已成功终止”),这可能特别烦人!”)。

使用无效的东西隐式地强制错误

console.log('this code gets executed');
fail;
console.log('this code is never reached');

除了“失败”之外,您实际上可以使用代码中不存在的任何东西,甚至是类似的东西,您知道... exit死亡

优点:代码不会显示错误,因此程序员阅读代码时不会思考< /em> 将构造视为“错误”。
缺点:一切!

  1. 使用无效的构造来突破脚本确实是混乱且草率的。 它只适用于代码混淆和欺骗试图阅读代码并因错误而感到困惑的用户。
  2. 不保证所有符合 ECMAScript 的环境都会观察到此类行为(例如:Codepen 正确地将不存在的语言结构标记为错误并拒绝运行脚本)。
  3. 即使现在是这样,将来也可能不是这样。
  4. 当使用第三方工具时(其中一些可能不是立即显而易见的,即它们会自动包含在内,而不会向 JS 程序员明确通知),可能存在已命名为 的东西失败退出死亡或任何被选择导致错误的东西,这会给程序员带来不可预测的结果(谁期望执行中止,而不是使用他们不知道之前已经定义的函数带来的一些未知的副作用)。 诚然,人们可能总是将自己的无效构造重命名为其他名称,但不能保证将来同样的情况不会再次发生!
  5. 与 throw new Error(...) 不同,它在语法上是正确的,即使在语义上它可能给出错误的概念(从数学上来说,不存在错误也是一个错误)本身的错误;如果您愿意,即“空错误”,即不属于可能错误集的错误;但是,这种哲学考虑超出了本讨论的范围) - 每个程序员都会使用 不同的脱离代码的无效构造(只需看看上面的答案,它们都使用相同的技术,但不知何故,那些编写答案的人似乎没有意识到它们都是同一概念的变体...... ),这将使不同程序员编写的代码几乎无法维护。
  6. Linters、语法检查器和其他类似的自动化工具会因此而窒息。 在使用自动化工具检查错误并仅发布“干净”代码的项目中尤其如此——例如,在 GitHub/GitLab/Bitbucket/Gitea/您使用的任何存储库上发布的任何开源解决方案; 或者基本上任何名副其实的软件公司的所有内部编程工具。

因此,很可能,这是第二个最糟糕的可能方法(我在这里看到的最糟糕的方法是建议无限循环以避免进一步的代码执行......)。

浏览器环境之外的 JavaScript

同样,那里没有通用标准; 但由于很可能大多数浏览器外的JavaScript正在Node.js下运行,@not2qbit的答案 应该可以解决问题

console.log('this code gets executed');
process.exit(0);  // 0 means no error; 1 and greater signifies some sort of error. 
console.log('this code is never reached');

优点:这与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 or die() (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:

(function () {
    console.log('this code gets executed');
    return;
    console.log('this code is never reached');
})();

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 the C 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

console.log('this code gets executed');
throw new Error("<write here some reason for exiting>");
console.log('this code is never reached');

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

console.log('this code gets executed');
fail;
console.log('this code is never reached');

Instead of "fail" you can essentially use anything which doesn't exist in your code, even something like, you know... exit or die.

Pros: The code does not show an error, so programmers reading the code will not think of the construct as an "error".
Cons: Everything!

  1. Using an invalid construct to break out of a script is really messy and sloppy. It's only good for code obfuscation and tricking the user who is trying to read it and gets baffled by the errors.
  2. It's not guaranteed that such behaviour will be observed by all ECMAScript-compliant environments (one example: Codepen correctly flags inexistent language constructs as errors and refuse to run the script).
  3. Even if it is now, it might not be the case in the future.
  4. When using third-party tools (some of which might not be immediately obvious, i.e. they're automatically being included without giving explicit notice to the JS programmer), there might exist something already named as fail or exit or die 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!
  5. Unlike 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.
  6. Linters, syntax checkers, and other such automated tools will choke on this. This is especially true in projects using automated tools to check for errors and only publish "clean" code — as, say, any open-source solution published on GitHub/GitLab/Bitbucket/Gitea/whatever repository you use; or on essentially all internal programming tools of any software house worthy of its name.

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:

console.log('this code gets executed');
process.exit(0);  // 0 means no error; 1 and greater signifies some sort of error. 
console.log('this code is never reached');

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.

抽个烟儿 2024-07-20 20:42:04

我使用这段代码来停止执行:

throw new FatalError("!! Stop JS !!");

虽然您会收到控制台错误,但它对我很有用。

i use this piece of code to stop execution:

throw new FatalError("!! Stop JS !!");

you will get a console error though but it works good for me.

挽心 2024-07-20 20:42:04

我正在使用 iobroker 并轻松地停止脚本

stopScript();

I am using iobroker and easily managed to stop the script with

stopScript();
寂寞陪衬 2024-07-20 20:42:04

这是一个例子,
如果存在条件,则终止脚本。
我在我的 SSE 客户端 javascript 中使用它,如果

<script src="sse-clint.js" host="https://sse.host" query='["q1,"q2"]' ></script>

无法从 JSON 解析中正确解析......

if( ! SSE_HOST  ) throw new Error(['[!] SSE.js: ERR_NOHOST - finished !']);

无论如何,总体思路是:

if( error==true) throw new Error([ 'You have This error' ,  'At this file', 'At this line'  ]);

这将终止/终止你的 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

<script src="sse-clint.js" host="https://sse.host" query='["q1,"q2"]' ></script>

canot be parsed right from JSON parse ...

if( ! SSE_HOST  ) throw new Error(['[!] SSE.js: ERR_NOHOST - finished !']);

... anyway the general idea is:

if( error==true) throw new Error([ 'You have This error' ,  'At this file', 'At this line'  ]);

this will terminate/die your javasript script

完美的未来在梦里 2024-07-20 20:42:04

只需创建一个 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.

友欢 2024-07-20 20:42:04

在大多数情况下不适用,但我在浏览器中运行了很多异步脚本,并且作为一种黑客手段,我

window.reload();

阻止了一切。

Not applicable in most circumstances, but I had lots of async scripts running in the browser and as a hack I do

window.reload();

to stop everything.

菊凝晚露 2024-07-20 20:42:04

此代码将停止当前窗口中所有 JavaScript 的执行:

    for(;;);

示例

console.log('READY!');

setTimeout(()=>{

  /* animation call */ 
  div.className = "anim";

  console.log('SET!');

  setTimeout(()=>{

    setTimeout(()=>{
      console.log('this code will never be executed');
    },1000);

    console.log('GO!');

    /* BOMB */
    for(;;);

    console.log('this code will never be executed');

  },1000);

},1000);
#div {
  position: fixed;
  height: 1rem; width: 1rem;
  left:   0rem; top:   0rem;
  transition: all 5s;
  background: red;
}
/* this <div> will never reached the right bottom corner */
#div.anim {
  left: calc(100vw - 1rem);
  top:  calc(100vh - 1rem);
}
<div id="div"></div>

This code will stop execution of all JavaScripts in current window:

    for(;;);

Example

console.log('READY!');

setTimeout(()=>{

  /* animation call */ 
  div.className = "anim";

  console.log('SET!');

  setTimeout(()=>{

    setTimeout(()=>{
      console.log('this code will never be executed');
    },1000);

    console.log('GO!');

    /* BOMB */
    for(;;);

    console.log('this code will never be executed');

  },1000);

},1000);
#div {
  position: fixed;
  height: 1rem; width: 1rem;
  left:   0rem; top:   0rem;
  transition: all 5s;
  background: red;
}
/* this <div> will never reached the right bottom corner */
#div.anim {
  left: calc(100vw - 1rem);
  top:  calc(100vh - 1rem);
}
<div id="div"></div>

只是我以为 2024-07-20 20:42:04

我使用 return 语句而不是 throw ,因为 throw 在控制台中给出错误。 最好的方法是检查条件,

if(condition){
 return //whatever you want to return
}

这只是停止该行程序的执行,而不是在控制台中给出任何错误。

i use return statement instead of throw as throw gives error in console. the best way to do it is to check the condition

if(condition){
 return //whatever you want to return
}

this simply stops the execution of the program from that line, instead of giving any errors in the console.

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