是否可以停止JavaScript执行? [英] Is it possible to stop JavaScript execution?

查看:390
本文介绍了是否可以停止JavaScript执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以某种方式停止或终止 JavaScript ,以防止任何在没有重新加载浏览器的情况下进一步执行基于JavaScript的执行?

Is it possible in some way to stop or terminate JavaScript in a way that it prevents any further JavaScript-based execution from occuring, without reloading the browser?

我在想一个等价的 exit()在PHP中。

I am thinking of a JavaScript equivalent of exit() in PHP.

推荐答案

简答:

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

如果您想了解更多信息,请继续阅读。

If you want to know more, keep reading.

表达式您的代码中的调试器; 将暂停页面执行,然后您的浏览器的开发人员工具将允许您在页面冻结时查看页面的状态。

The expression debugger; in your code, will halt the page execution, and then your browser's developer tools will allow you to review the state of your page at the moment it was frozen.

不要试图阻止一切,让你的代码处理错误。通过谷歌搜索了解例外 s。它们是一种智能的方法,可让您的代码跳转到错误处理程序,而无需使用繁琐的if / else块。

Instead of trying to stop everything, let your code handle the error. Read about Exceptions by googling. They are a smart way to let your code "jump" to error handling procedures without using tedious if/else blocks.

阅读完它们后,如果您认为中断了整个代码绝对是唯一的选择,抛出一个不会被捕获的异常,除了在你的应用程序的root范围内是解决方案:

After reading about them, if you believe that interrupting the whole code is absolutely the only option, throwing an exception that is not going to be "caught" anywhere except in your application's "root" scope is the solution:

// creates a new exception type:
function FatalError(){ Error.apply(this, arguments); this.name = "FatalError"; }
FatalError.prototype = Object.create(Error.prototype);

// and then, use this to trigger the error:
throw new FatalError("Something went badly wrong!");

请确保您没有 catch()阻止任何异常的块;在这种情况下修改它们以重新抛出你的FatalError异常

be sure you don't have catch() blocks that catch any exception; in this case modify them to rethrow your "FatalError" exception:

catch(exc){ if(exc instanceof FatalError) throw exc; else /* current code here */ }



当任务完成或任意事件发生时?



return; 将终止当前函数的执行流程。

When a task completes or an arbitrary event happens?

return; will terminate the current function's execution flow.

if(someEventHappened) return; // Will prevent subsequent code from being executed
alert("This alert will never be shown.");

注意:返回; 仅适用于函数。

...你可能想知道如何停止异步代码也是如此。这是通过 clearTimeout clearInterval 。最后,停止 XHR Ajax )请求,您可以使用 xhrObj.abort()方法(可用于 jQuery 以及)。

...you may want to know how to stop asynchronous code as well. It's done with clearTimeout and clearInterval. Finally, to stop XHR (Ajax) requests, you can use the xhrObj.abort() method (which is available in jQuery as well).

这篇关于是否可以停止JavaScript执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆