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


当前回答

放置调试器;关键字,在你想要停止执行的JavaScript代码。然后打开您喜欢的浏览器的开发人员工具并重新加载页面。现在它应该自动暂停。打开工具的Sources部分:调试器;关键字高亮显示,您可以选择恢复脚本执行。

我希望这能有所帮助。

更多信息请浏览:

https://developer.mozilla.org/de/docs/Tools/Debugger http://www.w3schools.com/js/js_debugging.asp

其他回答

在我的例子中,我使用window.stop。

window.stop()在当前浏览上下文中停止进一步的资源加载,相当于浏览器中的'stop'按钮。 由于脚本的执行方式不同,此方法不能中断其父文档的加载,但它将停止其父文档的图像、新窗口和其他仍在加载的对象。 用法:window.stop (); (源)

退出JS或Node脚本的方法有很多。以下是最相关的:

// 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);

如果你在REPL中(即在命令行上运行node之后),你可以输入.exit退出。

这段代码将停止当前窗口中所有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>

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

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

不能直接从JSON解析…

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'  ]);

这将终止/死亡你的javascript脚本

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