How to debug or narrow down logic errors? - javascript

I am trying to debug this game I am making. Something is wrong with the for loops and I do not know what it is; essentially I am trying to get my rectangles to spawn on the canvas after the user clicks ready. What are some ways to debug logic errors? Doing this over khanacademy.
When I println the drawRects function. Console says infinite loop and points to my for loops.
When I click ready, the console increases by 1 each time so I know the levelUp function is working.
I cant post another link because not enough rep, but when I println randomRects, nothing appears on the console.
Therefore, I believe it is safe to assume something is wrong with my for loops, because the levelUp function works but the random rectangles are not appearing. What are other debugging techniques I can use to narrow down the problem?

You debug a problem by finding out exactly what the code is doing.
There are a few ways to do that:
Use your head. This is your first line of defense. Run through the code in your head, or better yet with a piece of paper and a pencil. Use some example values for your input, and walk through line by line and see what the code would do. Talk out loud, write stuff down, and do this over and over again. This is a huge part of being a programmer.
Use a console. Processing has a println() function that should go to your JavaScript console in your browser. This is your new best friend. Print out the values of any variables you want to know about, like this:
println("x: " + x);
Or a simple println("here") inside an if statement can tell you whetehr that if statement is executing. Combine this with approach one to really check all of your assumptions.
Use a debugger. If all else fails, step through your code with a debugger. This is basically using a computer to do the first two approaches.
In reality, you'll use a combination of all of the above to debug a problem. But the basic idea is this: you need to understand what your code is doing. You do that by first running through the code in your head or on a piece of paper, and you test any assumptions or anything you aren't sure by printing stuff out.

Related

Stopping Node.js endless loop from on html button click

is it somehow possible to stop a long computation (in this example an endless loop) on a node.js webserver from HTML?
At the moment, I have two buttons (start and stop). The start button emits the function started on button click as follows:
function started(){
socket.emit('started');
}
and on the server.js:
client.on('started',function(){
while(!cancel)
{
}
});
How can I exit the loop from clicking the stop button?
Well, you don't really show us enough code, but you probably can't do this. node.js is single-threaded event driven system. As long as you are in the middle of a while loop, you can't get any more events so you can't ever process anything that from the client that would change the cancel variable.
The only way this could work (though it's probably still undesirable coding on the server) is if your own server code inside the loop could change the cancel variable without getting any new events from the outside world to cause the loop to stop.
If you're relying on some other event to come into the server to change that flag, this could never work. The whole design also appears to imply that a server is only serving the needs of one user which is also likely an improper design for a server.
This particular question as posted right now is an XY problem, where you failed to explain your overall problem you're trying to solve, but instead described some issue you ran into in your particular attempted solution. That prevents us from helping you with the real problem and, in this case, all we can really tell you is that this is a wrong solution and will not work. Please don't post XY problems. Tell us your real problem. It's perfectly fine to show us your attempted solution and what issues you ran into with it, but only after you've explained the overall problem you're trying to solve. That allows us to help you with higher level and better solutions that you haven't even thought of to ask about yet.
We could only help with a proper solution to your problem if you explained the actual top level problem and showed us a bunch more code.

Is there any chance to find source of javascript alert?

I'm working in a large project that was developed for several years and had tons of code. Recently uninformative alert start to appear. It just says Undefined. I need to find the source of this alert. Is the any chance to make something like "breakpoint on alert"? I want to see the source of this alert.
One possibility is to redefine alert function. I tried to make it in firefox without any success.
I'd go with redefining window.alert right at the start of the code for this type of development purposes.
window.alert = function(e){ console.warn( "Alerted: " + e ); }
This will give You a line number for sure. ( Tested on chrome console )
This is an old question, but thought I would help out with a simpler solution. A very easy way in Chrome to find the source is by placing a debug in the console on window.alert:
debug(window.alert)
This will break on alert and take you to the source. In general, using console with debug(fname) will break whenever the function fname is called.
As a continuation to Vsevolod's method, in FireBug over Firefox for example, you could place one conditional breakpoint on each and every alert(), and see which one fires off, then go up the callstack shown by FireBug.
The condition could be "typeof whatever_variable_is_displayed == 'undefined'".

Debugging Javascript. Is it possible to stop at the next file?

I am working with angular.js, and when I have some very, very wierd bugs with angular, I get stuck stepping through debugger hell.
Is there a way to have the Javascript console break on the first line of the next file accessed?
For instance, say I stepped through into angular.js.
Instead of stepping through angular and trying to get to the first line referenced of a next file, say "myFile.js," I would just like to tell the Javascript console to stop once it reaches a line of code from a different file than it is on right now, say, stop once it hits "myFile.js", or stop when it hits a line on anything other than the file "angular.js."
I have not mentioned any specific browser, for the fact that I assume that you may be able to do this with one browser and not the other.
I also understand that I should know my code well enough to know what the next line in the next file referenced should be, but the project I am working with is quite dynamic and it takes a lot of brain-power to figure out which line of which file I will actually hit next (ugh...)

Determining why Firebug won't gray/green lines

I'm tearing my hair out here due to Firebug's seeming propensity to refuse to hit breakpoints in critical sections where it would be really, really helpful to be able to step through the code to help see what is going on. I have read elsewhere that Firebug won't hit a breakpoint if the line number isn't the right color: it used to be green, but lately I notice it seems to be the difference between light gray and dark grey, where light-gray lines are the ones the Firebug won't break on.
I am looking for any suggestions as to how to get Firebug to recognize that it should be able to break on a line. Often it will refuse to honor breakpoints on ten or twenty lines in a row, as if it suddenly got confused parsing a function and just gave up until the function was over. In some cases, simply commenting out one line (and then reloading of course) makes Firebug suddenly recognize the rest of the function, but without any rhyme or reason that I can see, even to the point that simply adding something innocuous like an extra semi-colon makes it go back to not recognizing the lines again. In some cases it seems that do/while loops confuse it, but even in a function without such a loop I am currently having trouble.
I have already tried all the other things I could find in other threads, such as resetting all, restarting the browser, using the latest version, etc.
Update: In one case I was able to get Firebug to recognize lines by changing:
do {
...
} while (condition)
to
while (1) {
...
if (!(condition)) break
}
Firefox 23 / Firebug 1.11.4
Update: It seems that whenever I find a section of code like this, I can get the problem to go away by creating a new empty javascript file (adding a reference in the HTML file) and moving the affected function to that file. Suddenly the lines get greened (it's back to green again now, no idea why...)

How can you debug JavaScript which hangs the browser?

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.
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 next using FireBug.
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.
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.
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.
You can then add additional console log in the code between the two steps to search deeply for the problem, until you find it.
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:
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".
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.
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).
Firebug Wiki page: http://getfirebug.com/wiki/index.php/Debugger;_keyword
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 ...
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.
Install Google Chrome, go to your page, press f12 and the developer console will popup. Then select the Scripts button, 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-point will 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 2º button (or the button after pause to step over) or the 3º 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.
Google Chrome debugger is far better than firebug and faster. I made the change from firebug and this is really great! ;)
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:
<textarea id='txtLog' ...></textarea>
<script>
...
function log(str) {
$('#txtLog').append(str + '\n');
}
log("some message, like 'Executing Step #2'...");
...
</script>
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!.
Then split that in half, etc etc until you find the culprit.
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
Besides using manual log output and the debugger it might sometimes be helpful to log each and every function call to track down where the loop occurs. Following snippet from Adding console.log to every function automatically might come in handy to do so ...
function augment(withFn) {
var name, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
window[name] = (function(name, fn) {
var args = arguments;
return function() {
withFn.apply(this, args);
return fn.apply(this, arguments);
}
})(name, fn);
}
}
}
augment(function(name, fn) {
console.log("calling " + name);
});
I know this question is old, but in VS2013 and you can press the pause button and get a full JS stack trace. This was driving me crazy because the loop was inside angular, so I couldn't really put in alerts, break points, etc. because I had no idea where to put them. I don't know if it works with the free express edition, but it's worth a shot.
I've also read that Chrome has a pause function, so that could be an option, but I haven't tried it myself.
I ran into same problem and that's how I resolved it.
Check Console for errors and fix them
Some time console even is hanging
Check for all the loops if the one is infinite
Check for recursive code
Check for the code which is dynamically adding elements to document
Use break points in your console
Use some console logging i.e log the suspected code blocks
Something I don't really see in these answers is that you can do e.g.:
let start;
let end;
//This would represent your application loop.
while (true) {
start = performance.now();
//Loop code.
//...
end = performance.now();
//Measured in ms.
if (end - start > 1000) {
//Application is lagging! Etc.
}
}
In this manner, you can perhaps detect when your application is starting to perform poorly etc.
https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

Categories