是否有可能以某种方式停止或终止JavaScript,以防止任何进一步的基于JavaScript的执行发生,而无需重新加载浏览器?

我正在考虑在PHP中等价于exit()的JavaScript。


当前回答

在JavaScript函数中定义一个变量,如果你想执行这个函数,将这个变量设置为1,如果你想停止它,将它设置为0

var execute;
function do_something()
{
if (execute == 1)
{
// execute your function
}
else
{
 // do nothing
}
}

其他回答

No.

即使抛出异常,也只会终止当前的事件循环。传递给setTimeout或DOM/XMLHttpRequest事件处理程序的回调在时间到来时仍将运行。

如果你在一个函数中,你可以使用return退出它;但这不会停止调用该函数的父函数的执行。

在JavaScript函数中定义一个变量,如果你想执行这个函数,将这个变量设置为1,如果你想停止它,将它设置为0

var execute;
function do_something()
{
if (execute == 1)
{
// execute your function
}
else
{
 // do nothing
}
}

我知道这很老了,但我想这么做,我发现了,在我看来,一个稍微改进的投掷答案的解。只是暂时抑制错误消息,然后使用setTimeout重新激活它们:

setTimeout(function() {
    window.onerror = function(message, url, lineNumber) {  
        return false;
    };
}, 50); // sets a slight delay and then restores normal error reporting
window.onerror = function(message, url, lineNumber) {  
    return true;
};
throw new Error('controlledError');

类似这样的方法可能有用:

function javascript_abort()
{
   throw new Error('This is not an error. This is just to abort javascript');
}

从这里开始:

http://vikku.info/codesnippets/javascript/forcing-javascript-to-abort-stop-javascript-execution-at-any-time/