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


当前回答

我使用ibroker和容易地设法停止脚本

stopScript();

其他回答

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

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

虽然你会得到一个控制台错误,但这对我来说很好。

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

如果你在脚本中使用任何未定义的函数,那么脚本将由于“Uncaught ReferenceError”而停止。我已经尝试了以下代码和执行的前两行。

我认为,这是停止剧本的最好方法。如果有任何其他方式,请评论我。我还想知道另一种最好最简单的方法。BTW,我没有得到退出或死亡内置函数在Javascript像PHP终止脚本。如果有人知道,请告诉我。

alert('Hello');

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

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

alert('bye');

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

这段代码将停止当前窗口中所有javascript的执行:

(,);

例子

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>

简单地创建一个BOOL条件, 这里不需要复杂的代码。

即使你把它变成true/或多次, 它会给你一条解,而不是多条解 基本上就是这么简单。