简体   繁体   English

如何在 JavaScript 中终止脚本?

[英]How to terminate the script in JavaScript?

How can I exit the JavaScript script much like PHP's exit or die ?我怎样才能像 PHP 的exitdie一样退出 JavaScript 脚本? I know it's not the best programming practice but I need to.我知道这不是最好的编程实践,但我需要这样做。

"exit" functions usually quit the program or script along with an error message as paramete. “退出”函数通常会退出程序或脚本,并带有错误消息作为参数。 For example die(...) in php例如 php 中的 die(...)

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: JS 中的等价物是使用throw关键字发出错误信号,如下所示:

throw new Error();

You can easily test this:您可以轻松测试:

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

x
>>>undefined
m
>>>100

JavaScript equivalent for PHP's die . 相当于 PHP 的die JavaScript BTW it just calls exit() (thanks splattne):顺便说一句,它只是调用exit() (感谢 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 '';
}

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".这样,当您想停止程序时,您可以使用“返回”。

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.对调试/测试的某些方面很有用。

There are many ways to exit a JS or Node script.很多方法可以退出 JS 或 Node 脚本。 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 (ie after running node on the command line), you can type .exit to exit.如果您在REPL 中(即在命令行上运行node之后),您可以键入.exit退出。

Place the debugger;放置debugger; keyword in your JavaScript code where you want to stop the execution. JavaScript 代码中要停止执行的关键字。 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;打开工具的Sources部分: debugger; keyword is highlighted and you have the option to resume script execution.关键字突出显示,您可以选择恢复脚本执行。

I hope it helps.我希望它有帮助。

More information at:更多信息请访问:

就我而言,我使用了window.stop API,就像单击浏览器上的 X 按钮一样:

window.stop();

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有关 Chrome 断点信息,请单击此处
For Firefox break points info click here有关 Firefox 断点信息,请单击此处
For Explorer break points info click对于 Explorer 断点信息,请单击
For Safari break points info click here有关 Safari 断点信息,请单击此处

*Note - this information is a little outdated you may use worker threads or web worker off main thread to send messages early before completing the function essentially you can return early the message that you want and then from your receiver you would recall. *注意-此信息有些过时,您可以在完成功能之前使用辅助线程或Web辅助线程在主线程之外尽早发送消息,基本上,您可以尽早返回所需的消息,然后从接收者中回想起。 You can also do something like (return (callchain(a,b,c,d))()) or just nest multiple returns in if statements and turn on a flag to enter an if statement executing return early. 您还可以执行类似(return(callchain(a,b,c,d))())的操作,或者只是将多个return嵌套在if语句中,然后打开一个标志以输入一个if语句,尽早执行return。 throw() may have some performance implications and I do not think the browser can properly optimize the code when it compiles if it has throw. throw()可能会影响性能,并且我认为浏览器在编译时如果抛出异常,则无法正确优化代码。

With that said: This answer provides details utilizing throw() and added structure that will help solve this and other early exit, exceptions, process control, and sequential function handling needs in modular javascripts. 话虽如此:该答案提供了利用throw()和添加的结构的详细信息,这些结构将有助于解决模块化javascript中的此问题和其他早期退出,异常,过程控制以及顺序函数处理的需求。 Solution provides closure examples. 解决方案提供了关闭示例。 This answer assumes that the individual would like other scripts on the page to continue to run after the script in question has exited. 该答案假定该个人希望该脚本退出后,页面上的其他脚本继续运行。

Pen Throw Demo: https://codepen.io/alignedfibers/pen/VpMQzO 喷笔演示: https : //codepen.io/alignedfibers/pen/VpMQzO

Fiddle Throw Demo: http://jsfiddle.net/alignedfibers/cpe1o1yy/70/ 小提琴投掷演示: http : //jsfiddle.net/alignedfibers/cpe1o1yy/70/

<script>
    var safetyRun = (function(){
      var curExecution = null;
      var exceptionHandlers = {
        cleanup:function(){
          /*do exit cleanup*/
          console.log("Cleanup could set straglers to {}");
          return;
        }
      }
      var exitErr = function(errcode){
        curExecution.exNames.push("cleanup");
        throw new Error("EarlyExit");
      }
        var run = function(fun){
          curExecution = this;
          curExecution.exNames = [];
          fun(exitErr);
          for ( x in exNames){
            exceptionHandlers[x]();
          }
          return;
        }
        return run;
    })();
    var exitThisScript = function(exit){
      //write some modular code
      console.log("before exit");
      exit();
      console.log("after exit");
      return;
    }
    safetyRun(exitThisScript);
</script>

Above is a "CallRunner" that provides a very simple way to exit for free just by passing your function to the runner. 上面是一个“ CallRunner”,它提供了一种非常简单的方法,只需将函数传递给运行程序即可免费退出。

The variable naming in the fiddle may be confusing, the function named "fun" is the name used within safetyRun to reference the function we are trying to exit, and exitErr is the name used to reference the function we run to actually complete the exit. 小提琴中的变量命名可能会引起混淆,名为“ fun”的函数是safetyRun中用于引用我们要退出的函数的名称,而exitErr是用于引用我们为实际完成退出而运行的函数的名称。 Also a little confusing is: once the exitErr completes, the stack frame still is not released from the thread of control that called the function that we exited. 还有一点让人困惑的是:一旦exitErr完成,堆栈框架仍不会从调用我们退出的函数的控制线程中释放。 Because we still have thread of control we can use functions or error codes pushed on to an array in the exitErr function and call them itteratively before returning to allow any other functions to run. 因为我们仍然具有控制线程,所以我们可以使用在exitErr函数中推到数组上的函数或错误代码,并在返回之前调用它们,以允许其他函数运行。 This is allowing us to change any weights or make corrections or set any state needed that we can use to alert what error correction states need attention, send a log report or even complete challenging cleanup and autonomously fix the function in the background and itteratively call exitErr until it completes a return instead of a throw thus allowing the function we are trying to exit early complete, (suggest doing this offmainthread). 这使我们能够更改任何权重,进行更正或设置所需的任何状态,以用于警告需要注意的错误纠正状态,发送日志报告甚至完成具有挑战性的清理工作,并在后台自动修复该功能并自动调用exitErr直到它完成一个返回而不是抛出,从而使我们试图退出的功能提前完成(建议这样做是在offmainthread上完成)。 This "wrapper/harness" could be a good way to verify browser versions and stuff at the start of a function, you could even do a static or dynamic import here if you manage your own libraries or what ever you can really think of. 这种“包装器/线束”可能是在功能开始时验证浏览器版本和内容的好方法,如果您管理自己的库或您真正想到的东西,甚至可以在此处进行静态或动态导入。 Exit is only one fundemental function that can be made available for your function by wrapping it like this. 退出仅是一项基本功能,可以通过将其包装起来而使其对您的功能可用。

The code in the fiddle is a little dirty and not pretty, new es6 constructs can make this prettier. 小提琴中的代码有点脏而且不漂亮,新的es6构造可以使它更漂亮。 In addition I recommend that you call a harness generator at the top of this function and assign its result to a local var so the function you want to exit can look more like the code below. 另外,我建议您在此函数的顶部调用线束生成器,并将其结果分配给本地var,以便要退出的函数看起来更像下面的代码。 In order to keep thread of control without releasing the stack, you will still need need to have a harness.run(function(harness){/ MyVanillaFunc /}) to wrap your vanilla function, otherwise the below in theory should work. 为了在不释放堆栈的情况下保持控制线程,您仍将需要使用以下工具来包装您的香草函数,即需要使用arma.run(function(harness){/ MyVanillaFunc /}),否则理论上的以下内容应该可以工作。 Wrapping is exactly what I did in the exitEarly code above. 包装正是我在上面的exitEarly代码中所做的。

var rockStarFunction = new function (){
var harness = reducePublicStrapOnFromCache()._url(location);
return function(){ /*wrapper would wrap these internals*/
        harness.scriptContextChangeEvent();
        harness.imInteligentFunction("{slib_err-15346 : 'Cannot handle request, ::suggest(mesh//abc) exit back to pool'}");
        harness.exit();
        console.log("You should never get this far");
        return true;
    };
}

The solution I have provided here is the one I recommend if your intention is to build a javascript runner container with capabilities such as exit, assert, mock and the such built in. I think this is the better way to build this containership and make my functions transmittable. 如果您的意图是构建一个具有诸如exit,assert,mock等内置功能的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.最重要的是:您需要一个页面,在它抛出后立即通过电子邮件向您报告-您可以为此使用例如 Raven/Sentry。 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.在这种情况下,您还需要更新默认处理程序以过滤掉此类事件或将此类事件设置为在 Sentry 的仪表板上忽略。

window.stop(); 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.因此,您不能真正使用它来为用户提供页面的无 javascript 变体。

debugger;调试器;

Stops execution only with debugger opened.仅在调试器打开时停止执行。 Works great, but not a deliverable.效果很好,但不是可交付成果。

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).如果您正在寻找一种方法来强制终止页面上所有 Javascript 的执行,我不确定是否有官方认可的方法来做到这一点 - 这似乎是一种可能存在安全风险的事情(尽管老实说,我想不出这会是怎么回事)。 Normally in Javascript when you want your code to stop running, you just return from whatever function is executing.通常在 Javascript 中,当您希望代码停止运行时,您只需从正在执行的任何函数return (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. (如果return语句是函数中的最后一件事并且该函数不应该返回值,则它是可选的)如果有某种原因返回对您来说不够好,您可能应该在问题中编辑更多细节,以了解为什么认为您需要它,也许有人可以提供替代解决方案。

Note that in practice, most browsers' Javascript interpreters will simply stop running the current script if they encounter an error.请注意,在实践中,如果遇到错误,大多数浏览器的 Javascript 解释器将简单地停止运行当前脚本。 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.编辑:好的,根据 Ólafur 的说法,这可能不是一个很好的答案。 Although the die() function he linked to basically implements my second paragraph, ie it just throws an error.虽然他链接的die()函数基本上实现了我的第二段,即它只是抛出一个错误。

In JavaScript multiple ways are there, below are some of them在 JavaScript 中有多种方式,下面是其中一些

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; 

I know this is old, but if you want a similar PHP die() function, you could do:我知道这是旧的,但如果你想要一个类似的 PHP die()函数,你可以这样做:

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".上面的例子只会打印“Hello”。

To sum up different options:总结不同的选项:

window.stop();
debugger;
for(;;);
window.location.reload();

If page is loaded and you don't want to debug crash or reload:如果页面已加载并且您不想调试崩溃或重新加载:

throw new Error();

Additionally clear all timeouts另外清除所有超时

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

abort DOM/XMLHttpRequest中止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();

There're might be other stuff.可能还有其他东西。 Let me know in a comment.在评论中告诉我。

更新:由于你没有这个工作,只要catch了!

throw window.location.assign('dead.html');

This little function comes pretty close to mimicking PHP's exit().这个小函数非常接近于模仿 PHP 的 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

If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError".如果您在脚本中使用任何未定义的函数,则脚本将因“未捕获的 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.顺便说一句,我没有退出或死掉像 PHP 这样的 Javascript 中的内置函数来终止脚本。 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!!!');

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 :如果您只想停止执行更多代码而不“抛出”任何错误,您可以临时覆盖window.onerror ,如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.");

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

stopScript();

This code will stop execution of all JavaScripts in current window:此代码将停止执​​行当前窗口中的所有 JavaScript:

 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>

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)上面的代码可能是您不想要的:将整个脚本放在一个函数中可能会产生其他后果(例如,这样做,脚本将立即运行,并且在开发过程中无法从浏览器修改其部分,据我所知,在 Chrome 中)

Not applicable in most circumstances, but I had lots of async scripts running in the browser and as a hack I do在大多数情况下不适用,但我在浏览器中运行了很多异步脚本,并且作为一个 hack 我做了

window.reload();

to stop everything.停止一切。

This is an example, that, if a condition exist, then terminate the script.这是一个示例,如果条件存在,则终止脚本。 I use this in my SSE client side javascript, if the我在我的 SSE 客户端 javascript 中使用它,如果

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

canot be parsed right from JSON parse ...不能直接从 JSON 解析中解析...

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这将终止/终止您的 javasript 脚本

Simply create a BOOL condition , no need for complicated code here..只需创建一个 BOOL 条件,这里不需要复杂的代码..

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.如果即使您将其变为真/或多次,它也会为您提供一行解决方案/而不是多个解决方案-基本上就这么简单。

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.虽然你会收到一个控制台错误,但它对我很有用。

How can I exit the JavaScript script much like PHP's exit or die ?如何像PHP的exitdie那样退出JavaScript脚本? I know it's not the best programming practice but I need to.我知道这不是最佳编程实践,但我需要这样做。

i use return statement instead of throw as throw gives error in console.我使用 return 语句而不是 throw 因为 throw 在控制台中给出错误。 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.这只是停止从该行执行程序,而不是在控制台中给出任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM