我如何退出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.");
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法