如何调试导致浏览器挂起的 JavaScript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7289937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:39:07  来源:igfitidea点击:

How can you debug JavaScript which hangs the browser?

javascriptdebuggingbrowser

提问by JeanPaul

I'm working on a substantially large rich web page JavaScript application. For some reason a recent change is causing it to randomly hang the browser.

我正在开发一个非常大的富网页 JavaScript 应用程序。出于某种原因,最近的更改导致它随机挂起浏览器。

How can I narrow down where the problem is? Since the browser becomes unresponsive, I don't see any errors and can't Break on nextusing FireBug.

我怎样才能缩小问题所在?由于浏览器没有响应,我没有看到任何错误,也无法Break on next使用 FireBug。

回答by Jose Faeti

Instead of commenting the hell out of your code, you should use a debug console log.

您应该使用调试控制台日志,而不是对代码进行注释。

You should use the console.log()functionality provided by most modern browsers, or emulate it if you use a browser that doesn't support it.

您应该使用console.log()大多数现代浏览器提供的功能,或者如果您使用不支持它的浏览器来模拟它。

Every time you call console.log('sometext'), a log entry in the debug console of your browser will be created with your specified text, usually followed by the actual time.

每次调用 时console.log('sometext'),浏览器调试控制台中都会创建一个日志条目,其中包含您指定的文本,通常后跟实际时间。

You should set a log entry before every critical part of your application flow, then more and more until you find down what log isn't being called. That means the code before that log is hanging the browser.

您应该在应用程序流的每个关键部分之前设置一个日志条目,然后越来越多,直到找到没有被调用的日志。这意味着该日志之前的代码正在挂起浏览器。

You can also write your own personal log function with added functionalities, for example the state of some particular variable, or an object containing a more detailed aspect of your program flow, etc.

您还可以使用附加功能编写自己的个人日志函数,例如某些特定变量的状态,或包含程序流更详细方面的对象等。

Example

例子

console.log('step 1');

while(1) {}

console.log('step 2');

The infinite loop will halt the program, but you will still be able to see the console log with the program flow recorded until before the program halted.

无限循环将停止程序,但您仍然可以看到控制台日志,其中记录了程序停止之前记录的程序流程。

So in this example you won't see "step 2" in the console log, but you will see "step 1". This means the program halted between step 1 and step 2.

因此,在此示例中,您不会在控制台日志中看到“第 2 步”,但会看到“第 1 步”。这意味着程序在步骤 1 和步骤 2 之间停止。

You can then add additional console log in the code between the two steps to search deeply for the problem, until you find it.

然后,您可以在两个步骤之间的代码中添加额外的控制台日志,以深入搜索问题,直到找到为止。

回答by Ricardo Tomasi

You can add debugger;anywhere in your JS code to set a breakpoint manually. It will pause execution and allow you to resume/inspect the code (Firebug/FF).

您可以debugger;在 JS 代码中的任何位置添加手动设置断点。它将暂停执行并允许您恢复/检查代码 (Firebug/FF)。

Firebug Wiki page: http://getfirebug.com/wiki/index.php/Debugger;_keyword

Firebug 维基页面:http: //getfirebug.com/wiki/index.php/Debugger;_keyword

回答by Christopher Reid

I'm surprised this hasn't been properly answered yet, and the most voted answer is basically "put console logs everywhere until you figure it out" which isn't really a solution, especially with larger applications, unless you really want to spend all your time copy-pasting "console log".

我很惊讶这个问题还没有得到正确的回答,投票最多的答案基本上是“把控制台日志放在任何地方,直到你弄清楚为止”这不是一个真正的解决方案,尤其是对于较大的应用程序,除非你真的想花钱您一直在复制粘贴“控制台日志”。

Anyways, all you need is debugger;someone already mentioned this but didn't really explain how it could be used:

无论如何,您所需要的只是debugger;有人已经提到了这一点,但并没有真正解释如何使用它:

In chrome (and most other browsers), debugger;will halt execution, take you to the dev console, and show you the currently executing code on the left and the stack trace on the right. At the top right of the console there are some arrow like buttons. The first one is "resume script execution". The one we want is the next one "step over next function call".

在 chrome(和大多数其他浏览器)中,debugger;将停止执行,将您带到开发控制台,并在左侧显示当前正在执行的代码,在右侧显示堆栈跟踪。在控制台的右上角有一些类似箭头的按钮。第一个是“恢复脚本执行”。我们想要的是下一个“跳过下一个函数调用”。

Basically, all you need to do is put a debugger anywhere in your code, at a point where you know the page hasn't frozen yet, and then run it, and repeatedly click "step over next function call" which looks like an arrow jumping over a circle. It will go line by line, call by call, through the execution of your script until it hangs/gets stuck in an infinite loop. At this point, you will be able to see exactly where your code gets stuck, as well as all the variables/values currently in scope, which should help you understand why the script is stuck.

基本上,您需要做的就是在代码中的任何位置放置一个调试器,在您知道页面尚未冻结的地方,然后运行它,并重复单击看起来像箭头的“跳过下一个函数调用”跳过一个圆圈。它将逐行、逐个调用地执行您的脚本,直到它挂起/陷入无限循环。此时,您将能够准确地看到代码卡住的位置,以及当前范围内的所有变量/值,这应该有助于您理解脚本卡住的原因。

I was just racking my brain trying to find a hanging loop in some rather complex JS I'm working on, and I managed to find it in about 30 seconds using this method.

我只是绞尽脑汁试图在我正在处理的一些相当复杂的 JS 中找到一个挂环,我设法使用这种方法在大约 30 秒内找到了它。

回答by Darin Dimitrov

To isolate the problem you could start by removing/disabling/commenting different sections of your code until you have narrowed down the code to a small part which will allow you to find the error. Another possibility is to look at your source control check-in history for the different changes that have recently been committed. Hopefully you will understand where the problem comes from.

要隔离问题,您可以首先删除/禁用/注释代码的不同部分,直到将代码缩小到一小部分,以便您找到错误。另一种可能性是查看您的源代码管理签入历史记录,以了解最近提交的不同更改。希望你会明白问题的来源。

回答by kxr

Todays browsers Firefox/Seamonkey (Ctrl-Shift-I / Debugger / PAUSE-Icon), Chrome, ... usually have a builtin JS debugger with PAUSE button which works any time. Simply hit that when on a looping / CPU-intensive page, and most likely the "Call Stack" kind of pane will point you to the problem - ready for further inspection ...

今天的浏览器 Firefox/Seamonkey (Ctrl-Shift-I / Debugger / PAUSE-Icon), Chrome, ... 通常有一个内置的带有暂停按钮的 JS 调试器,可以随时工作。只需在循环/CPU 密集型页面上点击它,“调用堆栈”类型的窗格很可能会指向您的问题 - 准备好进一步检查......

回答by Totty.js

Install Google Chrome, go to your page, press f12and the developer console will popup. Then select the Scriptsbutton, then select your script(ex: myScript.js) from the dropdown in the top-left of the console. Then click on the first line (or a line where you think don't hangs) and a break-pointwill be made. After the javascript reaches your break-point click on one of the buttons of the top-right of the console (you will see a button like Pause symbol and then other 4 button). Press on the 2o button(or the button after pause to step over) or the 3o button (step in). Mouse over the buttons and they will explain to you what they mean. Then you will go in your code like this until it hangs and then you can debug it better.

安装谷歌浏览器,进入你的页面,按f12会弹出开发者控制台。然后选择脚本按钮,然后从控制台左上角的下拉列表中选择您的脚本(例如:myScript.js)。然后单击第一行(或您认为不会挂起的行),将创建一个断点。javascript 到达您的断点后,单击控制台右上角的按钮之一(您将看到一个类似于暂停符号的按钮,然后是其他 4 个按钮)。按 2o 按钮(或暂停后的按钮跳过)或 3o 按钮(步入)。将鼠标悬停在按钮上,它们会向您解释它们的含义。然后你会像这样进入你的代码,直到它挂起,然后你可以更好地调试它。

Google Chrome debugger is far better than firebug and faster. I made the change from firebug and this is really great! ;)

Google Chrome 调试器远比 firebug 好得多,而且速度更快。我从萤火虫进行了更改,这真的很棒!;)

回答by Trevor

I know it's primitive, but I like to sprinkle my js code with 'alert's to see how far my code is going before a problem occurs. If alert windows are too annoying, you might setup a textarea to which you can append logs:

我知道这是原始的,但我喜欢在我的 js 代码中添加“警报”,以查看我的代码在问题发生之前的进展情况。如果警报窗口太烦人,您可以设置一个可以附加日志的文本区域:

<textarea id='txtLog' ...></textarea>

<script>

...
function log(str) {
    $('#txtLog').append(str + '\n');
}
log("some message, like 'Executing Step #2'...");
...

</script>

回答by dougajmcdonald

In my experience, issues which cause the browser to become unresponsive are usually infinite loops or the suchlike.

根据我的经验,导致浏览器无响应的问题通常是无限循环之类的。

As a start point, investigate your loops for silly things like not incrementing something you later rely on.

作为起点,请检查您的循环是否存在愚蠢的事情,例如不增加您以后依赖的内容。

As an earlier poster said, other than that, comment out bits of code to isolate the issue. You 'could' use a divide and conquer methodology and near literally comment out half the pages JS, if it worked with a different error, you've probably found the right bit!.

正如较早的海报所说,除此之外,注释掉一些代码以隔离问题。你“可以”使用分而治之的方法,几乎​​从字面上注释掉一半的 JS 页面,如果它出现了不同的错误,你可能已经找到了正确的位置!。

Then split that in half, etc etc until you find the culprit.

然后将其分成两半等,直到找到罪魁祸首。

回答by Ihab Salem

I think you can Use Console Log like this

我想你可以像这样使用控制台日志

console.log(new Date() + " started Function Name or block of lines from # to #");

// functions or few lines of code

console.log(new Date() + " finished Function Name or block of lines from # to #")

By the end of running your webpage, you can identify the area that take so much time during executions, b

在运行您的网页结束时,您可以确定在执行过程中花费大量时间的区域,b

回答by Tofeeq

I ran into same problem and that's how I resolved it.

我遇到了同样的问题,这就是我解决它的方法。

  1. Check Console for errors and fix them
  1. 检查控制台是否有错误并修复它们

Some time console even is hanging

有时控制台甚至挂了

  1. Check for all the loops if the one is infinite
  2. Check for recursive code
  3. Check for the code which is dynamically adding elements to document
  4. Use break points in your console
  5. Use some console logging i.e log the suspected code blocks
  1. 如果循环是无限的,则检查所有循环
  2. 检查递归代码
  3. 检查动态添加元素到文档的代码
  4. 在控制台中使用断点
  5. 使用一些控制台日志记录,即记录可疑的代码块