Home  >  Article  >  Web Front-end  >  js implements breakpoint debugging

js implements breakpoint debugging

小云云
小云云Original
2018-03-30 15:42:582445browse

This article mainly shares with you js implementation of breakpoint debugging, mainly in the form of pictures and texts, hoping to help everyone.

1. What is breakpoint debugging? Is it difficult?

Breakpoint debugging is actually not that complicated. A simple understanding of no outbound calls is to open the browser, open sources, find the js file, and click on the line number. It seems very simple to operate, but in fact many people struggle with where to break the point? (Let’s look at a breakpoint screenshot first, taking the breakpoint of the Chrome browser as an example)



Do you remember the steps?


Open the page with chrome browser → Press f12 to open the developer tools → Open Sources → Open the js code file you want to debug → In the line number Click on OK! Congratulations on hitting your virginity breakpoint, haha~~


2. How to hit the breakpoint appropriately?

The operation of breaking points is very simple. The core question is, how to set breakpoints to find out the problems in the code? Let me continue to give an example to facilitate your understanding. Without further ado, here is the picture:


## Suppose we are now implementing a function to load more, as shown in the picture above, but now there is a problem with loading more functions. The data is not loaded after clicking. At this time What should be the first thing we think of? (Write the answer on a different line, so you can see what your first reaction is)

The first thing I thought of was, was my click successful? Are the methods in the click event run? Okay, if we want to know the answer to this question, let's try setting a breakpoint immediately. Where is the breakpoint? Think about it yourself first.

Continue with the picture above:


##Have you thought about it? That's right, since we want to know whether the click is successful, of course we add a breakpoint at the click event in the code. Remember not to add it on line 226, because the function in the click method is executed, not the selection on line 226. device. The breakpoint is now set, what do you do next? Think about it for yourself~

Continue with the picture above:


Then of course we go back and click the load more button, why? Forehead. . . If you ask, please allow me to use this emoticon

. How can I trigger a click event without clicking the load more button? How to execute the function in the click event without triggering the click event? Roaring. . But I believe that everyone will not ask such a low question~ No nonsense~

Let’s continue with the topic. The picture above is the situation after clicking the Load More button. We can see on the left The page on the side is covered by a translucent layer. There is a string of English and two buttons at the top of the page. The 227th line of code on the right is added with a background color. When this happens, let’s not worry about what those buttons mean in English. What does it do? What information did you get from this picture? Keep thinking about it~

If the above situation occurs, please note that the function in the click event is called, further indicating that the click event takes effect. Then our first "criminal suspect" for this problem has been eliminated.


Addition:

What should I do if the above situation does not occur? Does that mean that the click event did not take effect? So what causes the click event not to take effect? Think about it for yourself~

There are many reasons that may cause the click event not to take effect, such as multiple selector errors, syntax errors, the selected element is generated later, etc. How to solve it?

Selector error, you can continue to see the content of the console part, I think you will know how to deal with it

Grammar error, check it carefully, unfamiliar grammar can be compared with Baidu

The selected element is generated later. The simplest processing is to use the .on() method to process it. This stuff has event delegation processing. You can Baidu for details.


So where will the identity of the "criminal suspect" be locked next?

We turn our attention to the inside of the event. The click event is triggered, so the next problem is its internal function problem. If you want to ask why? Please give me a piece of tofu. . .

For example, I give you a pen and ask you to write. Then you write a word on the paper and find that the word does not come out. Why? You said I wrote it, but there are still scratches on the paper. Is it possible that the pen is out of ink or the nib is broken? This example is more similar to click loading. The action of writing is a click operation, and the internal function is the ink or pen tip. Do you understand~

Then let’s analyze the contents of the click event. It contains three sentences. The first sentence is to increase the variable i automatically, and the second sentence is to add to the button. An i tag, the third sentence is to call the method of requesting data.

Through the functions of these three sentences, we can place a larger part of the suspicion on the third sentence, and a smaller part on the first and second sentences. , some people may wonder, how can the second sentence be suspicious? Its function is just to add a label, which has no impact on the data at all. Indeed, this sentence has no impact on the data, but for strict consideration, it may still make mistakes. For example, what if it is missing a semicolon? Or is there a wrong symbol inside the sentence? It's often small problems like this that waste a lot of our time.

Okay, in order to further target the "criminal suspect", I would like to introduce a tool to you, which is also one of the two icons that appear in the picture above. See the picture below:


#The function of this small icon is called "Statement by Statement" "Execute" or "step by step execution" is a term that I personally understand. It means that every time you click it, the js statement will execute one sentence later. It also has a shortcut key, F10. The following picture demonstrates the effect after it is clicked:


##I clicked this button twice (or used the F10 shortcut key), and the js code was executed from line 227 to line 229, so I call it "statement-by-statement execution" or "step-by-step execution" . This function is very practical and will be used in most debugging.

It’s too late, I’ll continue writing tomorrow, the fun is yet to come~

———————————— ----------Dividing line--------------------


OK, keep writing!

As mentioned above, I clicked the "Execute statement by statement" button twice, and the code ran from line 227 to line 229. What do you think this means? Does this mean that grammatically speaking, the first two sentences are correct? Does it also mean that the first two sentences eliminate suspicion? I don't think so.

As we all know, loading more is a function of the next page, and the most important one is the page number value passed to the background. Whenever I click the load more button, the page number value will be Add 1, so if the data on the next page does not come out, is it possible that there is a problem with the page number value, which is the [i variable] (hereinafter referred to as i)? So how to check whether there is a problem with the page number? Let’s all think about it ourselves first.

The following will teach you two ways to view the actual output value of the page number i], the picture above:

The first method:


#The steps are as follows:

1. Still put a breakpoint on line 227 → 2. Click the Load more button → 3. Click the "Execute statement by statement" button once, and the js code will be executed to line 228 → 4. Use the mouse to select i++ ( What do you mean by selecting? It means you want to copy something, do you want to select it? Yes, this is the selection) → 5. After selecting, hover the mouse over the target, and you will see the result as shown above.

Second type:


##This method is actually similar to the first method, except that it outputs the value of i on the console. You only need to follow the first method to the third step → 4. Open the console at the same level as sources → 5. Enter i in the input field below the console → 6. Press the enter key.

In the second method above, the console is mentioned. We can call it a console or anything else. It doesn’t matter. The function of the console is very powerful. During the debugging process, we often need to know what the values ​​of certain variables are output, or whether we have selected the elements we want using a selector [$”.p”), etc., which can be printed on the console. come out. Of course, you can also use the first method directly.

Let me show you how to print the elements we want to select in the console. Pictured above~


# #Enter $(this) in the console to get the selected element. Yes, it is the object we clicked - load more button elements.

Here I would like to tell you my understanding of the console: This thing is a js parser, which is used by the browser itself to parse and run js, but The browser allows us developers to control the running and output of js during the debugging process through the console. Through the above two methods, you may think it is very simple to use, but I want to remind you, or it may be a confusion that some novices are more likely to encounter.


Confusion 1: When there is no break point, enter i in the console, and the console reports an error.

This should be a very common question for novices. Why can’t I directly output the value of the variable on the console without breaking the point? Personally, I understand that i is just a local variable at this time. If you do not set a breakpoint, the browser will parse all js. The console cannot access local variables, but only global variables, so at this time the console will report an error that i is not available. Definition, but when js sets a breakpoint, the console resolves to the function where the local variable i is located, and i can be accessed at this time.


Confusion 2: Why can things be printed when I directly enter $(".xxx") in the console?

It's very simple. The console itself is a js parser, and $(".xxx") is a js statement, so naturally the console can parse this statement and output the result.

After introducing the usage of the "Statement-by-Statement Execution" button and the console, let's finally introduce a button, as shown above:


I call this button the "Procedure-by-Procedure Execution" button, which is different from the "Statement-by-Statement Execution" button. The "Execute step by step" button is often used when one method calls multiple js files, and the js code involved is relatively long, this button will be used.

Above picture:


## Assume that in the above picture I only set a breakpoint on line 227, and then clicked the "Execute Statement by Statement" button all the way to line 229. At this time, if I clicked "Execute Statement by Statement" again What about the button? It will enter the js in the picture below:


##These are the contents of the zepto library file. There is nothing interesting to see. The operation inside is very complicated. We cannot always use the "Execute statement by statement" button, so you will find that you have been pressing it for most of the day. Still in the library file... What should I do at this time?

#In addition to setting a breakpoint on line 227, At the same time, we also set a breakpoint on line 237. When we run to line 229, click the "Execute step by step" button directly. You will find that js directly skips the library file and runs to line 237. You can use it yourself. Experience it.


Final summary:

This article mainly introduces " There are three tools: "Execute statement by statement" button, "Execute step by process" button, and console, as well as some ideas when debugging bugs. I won't go into details about the usage of the tools. Everyone knows how to use it. How to do it more reasonably? To use it, you still need to summarize and improve it through a lot of practice~

In fact, what I mainly want to talk about in this article is an idea for debugging bugs, but the selected examples involve too many things. . . . I’m afraid that it would be too long to write it down, so I simply selected a part to explain it to you. I don’t know if you will gain anything from me debugging a lot of things. If you do what I do in a real project, it will probably take you much longer to debug a bug than to write a script. In actual situations, we should develop the ability to get to the problem as soon as possible. , troubleshoot the problem in your mind by yourself, and find the most likely problem points. If you cannot quickly troubleshoot the most important points, then you can use the most troublesome but reliable method, use the "Execute statement by statement" button to Execute the entire js related to the problem in sequence. During the execution process, you will also clarify your ideas. At the same time, pay attention to whether the value of each variable and the element selected by the selector are correct. Generally speaking, do this once. The bugs are almost resolved.


##
So I personally think that our idea for debugging bugs should be as follows: first, whether js is successfully executed; secondly, whether there are logical problems, variable problems, parameter problems, etc. in js; finally, if the above are all No problem, look carefully at the various symbols. . .

OK~ That’s it for breaking points~ If you don’t understand, you can leave a message below~ And if you have any knowledge points that you don’t understand or are confused about the front-end, You can also leave a message below. When I have time, I will continue to write some documents for everyone’s messages~


Source: https://www.cnblogs.com/mqfblog/p/5397282.html



#Supplement: http://www.runoob.com/w3cnote/js-debugging-skills.html

Preface: Debugging skills are an essential skill in any technology research and development. Mastering various debugging skills will definitely get twice the result with half the effort at work. For example, it can quickly locate problems, reduce failure probability, help analyze logic errors, etc. Today, when Internet front-end development is becoming more and more important, how to reduce development costs and improve work efficiency in front-end development and master front-end development and debugging skills is particularly important.

This article will explain various front-end JS debugging skills one by one. Maybe you are already proficient in it, so let us review it together. Maybe there are methods you have never seen before, so you might as well learn them together. Maybe you don’t know how yet? Debugging, hurry up and take this opportunity to fill in the gaps.

1. Alert, a hard-core debugging master

It was still the era when the Internet had just started. The front-end of web pages was mainly focused on content display, and browser scripts could only When the page provides very simple accessibility functions. At that time, web pages mainly ran in browsers based on IE6, and the debugging function of JS was still very weak. It could only be debugged through the alert method built into the Window object. At that time, it should look like this:

js implements breakpoint debugging

It should be noted that the effect seen here is not the effect seen in the IE browser of the year, but the effect in the higher version of IE. In addition, it seems that there was no such advanced console back then, and the use of alert was also in the real page JS code. Although the debugging method of alert is very primitive, it did have its indelible value at the time, and even today, it has its place.

2. The new generation of debugging king Console

As JS can do more and more things in the Web front-end, its responsibilities are getting bigger and its status is also increasing. more and more important. The traditional alert debugging method has gradually been unable to meet the various scenarios of front-end development. Moreover, the debugging information that pops up in the alert debugging mode is not very beautiful, and it blocks part of the page content, which is really not very friendly.

On the other hand, for alert debugging information, statements like "alert(xxxxx)" must be added to the program logic to work properly, and alert will prevent the page from continuing to render. This means that after developers complete debugging, they must manually clear these debugging codes, which is really troublesome.

Therefore, the new generation of browsers Firefox, Chrome, including IE, have successively launched JS debugging consoles, supporting the use of a form similar to "console.log(xxxx)" to print debugging information on the console. It does not directly affect page display. Taking IE as an example, it looks like this:

js implements breakpoint debugging

Okay, goodbye ugly alert popup. And the rising stars, led by the Chrome browser, have expanded the Console with richer functions:

js implements breakpoint debugging

Do you think this is enough? The imagination of the Chrome development team really has to be admired:

js implements breakpoint debugging

Okay, let’s go off topic a little bit more. In short, the emergence of the console and the browser's built-in Console object has brought great convenience to front-end development and debugging.

Some people may ask, does such debugging code need to be cleaned after debugging is completed?

Regarding this issue, if you verify the existence of the console object before using it, it will not cause damage to the business logic without deleting it. Of course, for the sake of clean code, after debugging is completed, these debugging codes that have nothing to do with business logic should be deleted as much as possible.

3. JS breakpoint debugging

Breakpoint, one of the functions of the debugger, can interrupt the program where needed, thereby facilitating its analysis. You can also set a breakpoint during one debugging. Next time, you only need to let the program automatically run to the set breakpoint position, and then it can be interrupted at the last set breakpoint position, which greatly facilitates operation and saves time. ——Baidu Encyclopedia

JS breakpoint debugging is to add breakpoints to the JS code in the browser developer tools, so that the JS execution stops at a specific location, making it easier for developers to debug the code segment. analysis and logical processing. In order to be able to observe the effect of breakpoint debugging, we prepare a piece of JS code in advance:

js implements breakpoint debugging

The code is very simple, just define a function, pass in two numbers, and add After the last random integer, return the sum of the two numbers. Taking Chrome developer tools as an example, let's take a look at the basic method of JS breakpoint debugging.

3.1. Sources breakpoint

First of all, in the test code, we can see from the console output in the figure above that the code should be running normally, but why should it be Woolen cloth? Because a random number is added to the function, is the final result really correct? This is a meaningless conjecture, but suppose I want to verify it now: the two numbers passed in by the function, the random numbers added, and the final sum. So how to do it?

Method 1, the most common one mentioned before, whether using alert or console, we can verify it like this:

js implements breakpoint debugging

From the above figure, we find that Three lines of console code are added to the code to print the data variables we care about. In the end, the output results from the console (Console panel) can clearly verify whether the entire calculation process is normal, and then achieve our problem. verification requirements.

Method 2. The verification process of Method 1 has an obvious drawback, which is that it adds a lot of redundant code. Next, let’s see if it is more convenient to use breakpoints for verification. Let’s first look at how to add breakpoints. , and what the effect will be after the breakpoint:

js implements breakpoint debugging

As shown in the figure, the process of adding a breakpoint to a piece of code is "F12 (Ctrl + Shift + I) to open the development tools" - - "Click the Sources menu" - "Find the corresponding file in the tree on the left" - "Click the line number column" to complete the operation of adding/deleting breakpoints on the current line. After the breakpoint is added, refresh the page and JS execution stops at the breakpoint position. You will see all the variables and values ​​in the current scope on the Sources interface. You only need to verify each value to complete the verification requirements of our question.

Here comes the problem. Careful friends will find that when my code is executed to the breakpoint, the displayed values ​​​​of variables a and b have been added, and we cannot see the call to sum. The function is initially passed in 10 and 20. Then what should be done? It’s time to go back and learn some basic knowledge of breakpoint debugging. After we open the Sources panel, we will actually see the following content in the interface. Let’s follow the mouse trajectory to see what it means one by one:

From left to right, the functions represented by each icon are:

  • Pause/Resume script execution: Pause/resume script execution (program execution stops at the next breakpoint).

  • Step over next function call: Execute the function call to the next step (jump to the next line).

  • Step into next function call: Enter the current function.

  • Step out of current function: Jump out of the current execution function.

  • Deactive/Active all breakpoints: Close/enable all breakpoints (will not cancel).

  • Pause on exceptions: Automatic breakpoint setting for exceptions.

At this point, the function keys of breakpoint debugging are almost introduced. Next, we can look at our program code line by line and check the changes of each of our variables after each line is executed. As shown in the figure below:

js implements breakpoint debugging

As above, we can see that the variables a and b change from the initial value to the random value in the middle, and then finally calculate the sum and output it. The entire process of the final result is a matter of completing the verification requirements of the question design.

For the remaining function keys, we slightly change our test code and use a gif picture to demonstrate their use:

js implements breakpoint debugging

Needed here Note that the function of printing variable values ​​directly in the code area is a new function only added to newer versions of Chrome browsers. If you are still using an older version of Chrome browsers, you may not be able to directly print variable values ​​​​in the case of breakpoints. To view variable information, you can move the mouse over the variable name and pause briefly, and the variable value will appear. You can also use the mouse to select the variable name, then right-click "Add to watch" to view it in the Watch panel. This method also applies to expressions. In addition, you can also switch to the Console panel under a breakpoint, enter the variable name directly in the console, and press Enter to view the variable information. This part is relatively simple. Considering the space issue, no diagram demonstration will be given.

3.2. Debugger breakpoint

The so-called Debugger breakpoint is actually named by me myself. I don’t know how to use the professional terminology. Specifically, by adding a "debugger;" statement to the code, a breakpoint will be automatically reached when the code is executed. The next operation is almost exactly the same as adding breakpoint debugging in the Sources panel. The only difference is that you need to delete the statement after debugging.

Since the function is the same as adding breakpoints in the Sources panel except for the different ways of setting breakpoints, why does this method still exist? I think the reason is this: During development, we occasionally encounter asynchronous loading of html fragments (including embedded JS code), and this part of the JS code cannot be found in the Sources tree, so it cannot be added directly in the development tools. Breakpoint, then if you want to add a breakpoint to an asynchronously loaded script, then "debugger;" comes into play. Let’s see its effect directly through the gif:

js implements breakpoint debugging

4. DOM breakpoint debugging

DOM breakpoint, as the name suggests Add breakpoints on DOM elements for debugging purposes. In the actual use of break points, the effect is ultimately implemented within JS logic. Let’s take a look at the specific effects of each DOM breakpoint in turn.

4.1. Break on subtree modifications when the internal sub-nodes of the node change

As front-end development becomes more and more complex, front-end JS code becomes more and more complex. The more there are, the more complex the logic becomes. A seemingly simple Web page is usually accompanied by large sections of JS code, involving many operations of adding, deleting, and modifying DOM nodes. It is inevitable to encounter situations where it is difficult to locate the code segment directly through the JS code, but we can quickly locate the relevant DOM nodes through the Elements panel of the developer tools. At this time, locating the script through DOM breakpoints is particularly important. Specifically, let’s take a look at the gif demonstration:

js implements breakpoint debugging

The above figure demonstrates the effect of adding, deleting and exchanging sequence operations of ul sub-nodes (li) to trigger breakpoints . However, it should be noted that modifying attributes and content of child nodes will not trigger breakpoints.

4.2. Break on attributes modifications when node attributes change

On the other hand, as the business logic of front-end processing becomes more and more complex, the The storage dependence of some data is getting stronger and stronger, and storing temporary data in the (custom) attributes of DOM nodes is the preferred method for developers in many cases. Especially after the HTML5 standard enhanced custom attribute support (for example: dataset, data-*, etc.), attribute settings are used more and more, so Chrome developer tools also provide attribute change breakpoint support, the effect is roughly as follows:

js implements breakpoint debugging

#This method also needs to be noted that any operation on the properties of the child node will not trigger the breakpoint of the node itself.

4.3. Break on node removal

This DOM breakpoint setting is very simple and the triggering method is very clear - when the node is deleted . So usually this method should be used when executing the "parentNode.removeChild(childNode)" statement. This method is not used much.

The previously introduced debugging methods are basically the debugging methods we often use in daily development. If used properly, they can deal with almost all problems in our daily development. However, the developer tools also take into account more situations and provide more breakpoint methods, as shown in the figure:

5, XHR Breakpoints

Front-end in recent years Development has undergone earth-shaking changes, from being unknown at the beginning to being very popular today, Ajax drives rich Web applications, and mobile WebApp single-page applications are booming. All of this is inseparable from the XMLHttpRequest object, and "XHR Breakpoints" is a breakpoint debugging function designed for asynchronous use.

js implements breakpoint debugging

We can add breakpoint conditions for asynchronous breakpoints through the "+" sign on the right side of "XHR Breakpoints". When the asynchronous request is triggered, the URL meets this condition, JS Logic will automatically generate breakpoints. The breakpoint location is not shown in the demo animation. This is because the demo uses the ajax method encapsulated by jQuery. The code has been compressed and there is no visible effect. In fact, the location where the XHR breakpoint is generated is "xhr. send()" statement.

The power of XHR breakpoints is that you can customize breakpoint rules, which means that we can set breakpoints for a certain batch, a certain one, or even all asynchronous requests, which is very powerful. However, it seems that this feature is not used much in daily development, at least not by me. Thinking about it, there are probably two reasons: first, this type of breakpoint debugging requirement is not involved much in daily business; second, most front-end development at this stage is based on JS framework, and the most basic jQuery has also implemented Ajax. In order to ensure good encapsulation, few people encapsulate Ajax methods themselves. In order to reduce the code size, projects usually choose compressed code libraries, making XHR breakpoint tracking relatively difficult.

6. Event Listener Breakpoints

Event listener breakpoints are set according to the event name. When an event is triggered, the breakpoint is set to the location where the event is bound. Event listener breakpoints list all page and script events, including: mouse, keyboard, animation, timer, XHR, etc. It greatly reduces the difficulty of debugging event-related business logic.

js implements breakpoint debugging

The demo example demonstrates the breakpoint effect when the click event is triggered and when setTimeout is set. The example shows that when the click event breakpoint is selected, the breakpoints are triggered when both buttons are clicked, and when setTimeout is set, the "Set Timer" breakpoint is triggered.

Debugging is a very important link in project development. It can not only help us quickly locate problems, but also save our development time. Being proficient in various debugging methods will definitely bring many benefits to your career development. However, among so many debugging methods, how to choose one that suits your current application scenario requires experience and continuous trial and error accumulation.

Related recommendations:

js breakpoint debugging example explanation

Must-see js breakpoint debugging experience sharing

How to use js for breakpoint debugging?

The above is the detailed content of js implements breakpoint debugging. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn