我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。
当前回答
把“”;
是对这个概念的误用,但可能是唯一的选择。是的,您必须重置所有事件侦听器,就像接受的答案提到的那样。如果我是对的,你还需要一个单一的入口。
在它的顶部:你想要一个通过电子邮件向你报告的页面,你可以使用例如Raven/Sentry。但这意味着,你给自己制造了假阳性。在这种情况下,您还需要更新默认处理程序以过滤掉此类事件,或者在Sentry的仪表板上将此类事件设置为忽略。
window.stop ();
这在页面加载期间不起作用。它也会停止对页面的解码。所以你不能用它来为用户提供网页的无javascript变体。
调试器;
仅在调试器打开时停止执行。工作很好,但不能交付。
其他回答
在JavaScript中有多种方式,下面是其中的一些
方法1:
throw new Error("Something went badly wrong!");
方法2:
return;
方法3:
return false;
方法4:
new new
方法5:
使用上述方法编写自定义函数,并在需要的地方调用
注意: 如果您想暂停代码执行,您可以使用
debugger;
退出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脚本
即使在没有句柄、事件等的简单程序中,最好将代码放在主函数中,即使它是唯一的过程:
<script>
function main()
{
//code
}
main();
</script>
这样,当你想要停止程序时,你可以使用return。
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?