如何用Javascript终止脚本

我需要一个代码,这将退出js脚本很像PHP'退出'或'死'。 (我知道它不是最好的编程习惯,但我需要它)。

JavaScript相当于PHP的die 。 顺便说一句,它只是调用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 ''; } 

“退出”function通常退出程序或脚本,并附带错误消息作为参数。 例如死(…)在PHP中

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

JS中的等价物是用这样的throw关键字来表示一个错误:

 throw new Error(); 

你可以很容易地testing这个:

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

即使在没有句柄,事件等简单程序的情况下,最好是把代码放在“主”函数中,即使是唯一的程序:

 <script> function main() { //code } main(); </script> 

这样,当你想停止程序,你可以使用“返回”。

如果您正在寻找一种强制终止页面上所有Javascript的执行的方式,我不确定是否有官方认可的方式来做到这一点 – 这似乎是一种安全风险(尽pipe说实话,我想不出如何将这是我的头顶)。 通常在Javascript中,当你希望你的代码停止运行时,你只需从任何正在执行的函数中return 。 ( return语句是可选的,如果它是函数中的最后一个东西,并且函数不应该返回一个值)如果有一些原因返回对你来说不够好,你应该编辑更多的细节到你为什么认为你需要它,也许有人可以提供一个替代解决scheme。

请注意,实际上,大多数浏览器的Javascript解释器只会在遇到错误时停止运行当前脚本。 所以你可以做一些事情,比如访问一个未设置variables的属性:

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

可能会中止脚本。 但是你不应该依靠这个,因为这根本就不是标准,而且看起来真是一个可怕的做法。

编辑 :好的,也许这根本不是Ólafur的那么好的答案。 虽然他链接到die()函数基本上实现了我的第二段,即它只是抛出一个错误。

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

我希望它有帮助。

更多信息请见:

这个答案提供了详细的演示额外的框架,这将有助于解决这个和其他早期的退出,exception,过程控制和顺序function处理模块化javascript需求的需求。 解决scheme提供了closures示 这个答案假设个人希望在有问题的脚本退出后,页面上的其他脚本继续运行。

简单的解决scheme的实例在这里: https : //codepen.io/corpus_khu/pen/VpMQzO

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

以上是退出的一个非常简单的方法。 在将你的函数发送给这个“Runner”之前,我build议把你的函数包装在一个加载了一个线束的对象中,并且可以执行,testing工具应该向你的函数暴露exit()方法,被传递。

你需要build立一个良好的退出策略的例子可以在这里的github(文件:pseudo_threads2.js): https : //github.com/fromSpace/js-recursionwithevents-practice

现场演示版本: https : //fromspace.github.io/js-recursionwithevents-practice/

请注意,在pseudo_threads2.js中,函数simConstantMomentum()返回一个函数,该函数具有所有线束函数的词法范围variables。 相反,我build议你在这个函数的顶部调用一个线束生成器,并把它的结果赋给一个局部variables,这样当你完成的时候,你想要退出的函数看起来更像这样。

 var rockStarFunction = new function (){ var harness = reducePublicStrapOnFromCache()._url(location); return function(){ 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; }; } 

我在这里提供的解决scheme是我推荐的,如果你的目的是build立一个JavaScript的跑步者容器与退出,断言,模拟等内置的。我认为这是更好的方式来build立这个容器,使我function可传输。 – corpus_khu

如果你不在意这是一个错误,只需写:

 fail; 

这将停止你的主要(全局)代码进行。 对debugging/testing的某些方面有用。

就我而言,我使用了Window.stop API,就像在浏览器上点击Xbutton一样:

请参阅: https : //developer.mozilla.org/en/docs/Web/API/Window/stop

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

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

canon被parsing从JSONparsing…

 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脚本