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


当前回答

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

其他回答

在JavaScript中有多种方式,下面是其中的一些

方法1:

throw new Error("Something went badly wrong!");

方法2:

return;

方法3:

return false;

方法4:

new new

方法5:

使用上述方法编写自定义函数,并在需要的地方调用

注意: 如果您想暂停代码执行,您可以使用

debugger; 

Javascript可以在devtools中禁用:ctrl+shift+j跟随cltf+shift+p,然后输入disable Javascript

上述可能的选项:

window.stop(); // equivalent to the 'stop' button in the browser
debugger; // debugs
for(;;); // crashes your browser
window.location.reload(); // reloads current page

如果页面已加载,而你不想调试崩溃或重新加载:

throw new Error();

此外,清除所有超时

var id = window.setTimeout(function() {}, 0);
while (id--) {
    window.clearTimeout(id);
}

中止DOM - XMLHttpRequest

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(i, jqXHR) { 
        jqXHR.abort();  
        $.xhrPool.splice(i, 1); 
    });
}
$.ajaxSetup({
    beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR);
        if (i > -1) $.xhrPool.splice(i, 1); 
    }
});

删除所有事件监听器,包括内联监听器

$("*").prop("onclick", null).off();

这将删除脚本并重新创建没有事件的元素

$('script').remove();
$('*').each(function(){
    $(this).replaceWith($(this).clone());   
});

如果网页上没有jQuery,则复制粘贴源代码到控制台。

可能还有其他的东西。请在评论中告诉我。

即使在没有句柄、事件等的简单程序中,最好将代码放在主函数中,即使它是唯一的过程:

<script> 
function main()
{
//code

}
main();
</script>

这样,当你想要停止程序时,你可以使用return。

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

我希望这能有所帮助。

更多信息请浏览:

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

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