How can I test potentially "browser-crashing" JavaScript? - javascript

I've been having a crack at some of the problems over at http://projecteuler.net/ with JavaScript. I've been using a simple html page and running my code in script tags so I can log my results in the browsers' console. When experimenting with loops I sometimes cause the browser to crash.
Is there a better environment for me to do this kind of development?

a browser that has separate processes for each tab
debugger breakpoints
an if that breaks the loop if some threshold for time is hit

If you're running computationally expensive programs in your browser, you may want to look at using web workers. In short, they allow you to run code in a different thread which won't lock up the browser.

If you are just interested in running javascript programs as such, why don't you use something like node.js or even Rhino? That way you can easily log output without loosing it if it get into 'trouble'.

I can think of two ready possibilities:
1) Use a debugger that has breakpoints. Firebug is rather nice. Safari and Chrome also have some built-in debugging tools.
2) You could move your testing out of the browser using Mozilla Rhino and Env-js (see http://groups.google.com/group/envjs and http://github.com/thatcher/env-js )

All modern browsers (except Opera) should interrupt your script if it runs for more than 5-10 seconds (Source).
In Firefox you can even lower this threshold, if 10 seconds mean a too big punishment. Also note that this mechanism kicks in even when you run code from the Firebug console:
Stop Script on Firefox http://img819.imageshack.us/img819/9655/infloopsp.jpg
I think this feature alone should provide a pretty safe environment for these loopy experiments :)

There's nothing you can do to keep the browser from crashing other than fix bugs that cause the browser to crash.
You can at least mitigate the impact of the crash by using a browser like Chrome that generally segregates crashes in one tab from the others (so you lose only your own page), or just installing a separate browser specifically for testing.
In terms of keeping track of data that might have gone to the log, you might use a plugin like Firebug that has a built-in debugger so you can pause the script execution partway through and examine your variables, presumably before any crash occurs.

Related

How can I hit breakpoints (and see error line numbers) when debugging javascript on Android?

I'm trying to follow these instructions for debugging android javascript.
I am aware of How can I debug javascript on Android?, but it's not clear to me how (or if) I can hit breakpoints - either using Chrome on the Android device, or the Android browser.
I can see and 'inspect' the device OK:
But breakpoints don't get hit, nor can I see line numbers on the errors in the console:
Between these two problems, I'm not getting much useful information from the debugging experience! I have tried going to 'about:debug' in the android browser, and do see the debug options appear.
I will add that the js I am debugging works fine in the latest Chrome on the same Android device.
First off, it seems like there are a bunch of syntax errors that may be preventing mustache.js from executing at all - see if you can take care of those first.
I'd try setting a breakpoint on the next line down - line #9 - to see if anything in that IIFE is running at all.
Assuming you are using a module bundler (such as Webpack) in development (based on port 8080 in your screenshot), most likely the code you're trying to debug is executed via eval. In which case by the time you can see it in the devtools, it has already run.
You can either use the debugger statement in your code, or running in production mode - where there's a real script file being executed. In both cases, you should attach the remote debugger first, and only then navigate to your page (or refresh it).
I have now tried the same thing again, and this time didn't experience the problem. Unfortunately I can't put my finger on what the problem was exactly, as due to my dev machine dying I am running a new windows 10 installation, and potentially a different version of the Android SDK and ADB. The phone and android browser haven't changed.
Anyway, I can now set and hit breakpoints as I'd expect:
I also get better error descriptions and line numbers:
FWIW, the only problem that needed fixing was changing some 'let' declarations to 'var'.

Debugging error message: "A script on this page is causing Internet Explorer to run slowly"

One of my users is intermittently getting a dialog in IE 8 that says:
A script on this page is causing Internet Explorer to run slowly
This problem has been reported numerous times in the MSDN forums and other places on the web. For example:
http://social.msdn.microsoft.com/Forums/ie/en-US/0fdb7550-0a59-4553-a90e-1958475f2ce5/how-to-debug-a-script-on-this-page-is-causing-internet-explorer-to-run-slowly?forum=iewebdevelopment
http://social.msdn.microsoft.com/Forums/ie/en-US/dafffdd8-a390-4a3c-a904-867acaec298e/error-message-a-script-on-this-page-is-causing-internet-explorer-to-run-slowly-for-ie8?forum=whatforum
http://social.msdn.microsoft.com/Forums/ie/en-US/e9d16d2a-60e1-4d6f-8f80-0d981eab3a2e/a-script-on-this-page-is-causing-your-web-browser-to-run-slowly?forum=bingmapsajax
So, this question is a duplicate of those and many others. But it is an intentional duplicate, because I don't think any of those questions were answered in a way that helps a user (developer) to determine precisely what in his scenario causes the dialog to appear.
I know that based on this page:
http://support.microsoft.com/kb/175500
the dialog appears when a certain number of statements have executed since a new script begins execution (through a variety of means). By default the number of statements is 5,000,000 but this is configurable via a registry entry.
The general prescription to this problem is a combination of:
Write less code. Unfortunately, this is not always possible.
Use web workers. This is not an option for IE before IE 10, nor with
some mobile browsers.
Use setTimeOut, setInterval, event handlers, etc to break the
script(s) up. This is a legitimate strategy across all browsers.
So, I understand what the problem is in general terms, and I understand what the options are to solve the problem, again in general terms. The question is, how to determine what area(s) of the code are causing the dialog to appear for a specific user? Often this problem occurs with a very large code base (including third party libraries), so a manual review of the code base without some tooling support is not feasible.
Most browsers, including IE8 and later, have profiling tools that enable the developer to determine JavaScript CPU usage. With the exception of IE, other browsers decide a script is long running not based on the numbers of statements executed but rather the amount of time the script spent executing. To this end, the profilers available in (or as add ons) to the browsers can identify the percentage and usually raw time spent executing a function, both inclusively and exclusively for a function, and the results can be sorted accordingly. IE's profiler will also give you a count of how often a function is called. None of these profilers tell you how many statements of code within a function were executed during profiling; they tell you only how long was spent in the function and how many times the function was called. This doesn't help with IE's slow script dialog logic, which is based on the number of statements (not time) that were executed. There is sometimes a correlation between the time spent executing a function and the number of statements, but it is not a reliable relationship as of course different types of statements can take very different lengths of times to execute (e.g. many native JavaScript functions are faster than calls which update the DOM; both have the same statement count but the former executes faster than the latter, making examining %/raw time not very useful).
One approach I've used that is of some value is when the slow script dialog appears, start the debugger in IE (if not already started) and select the break on next statement command in the debugger. Then click the dialog button in the browser that allows the slow script to continue executing. At this point, the debugger is invoked and the developer can examine the call stack to determine what is executing at the time the slow script dialog appears. This is okay, but a very manual approach and there's no guarantee there aren't multiple scripts running that can at different times invoke the dialog.
An interesting idea I've seen suggested is to use a JavaScript code coverage tool to instrument the code base. There are multiple JavaScript code coverage options out there, but the ease of use of a browser extension that could dynamically instrument the code seems like an ideal solution. (Another interesting idea is to use a proxy server, for example http://siliconforks.com/jscoverage/manual.html; 'jscoverage --server --proxy', but I couldn't get this to work on virtually any website, except the the silicon forks website itself). There's a proof of concept one available for Chrome (http://googletesting.blogspot.ca/2011/10/scriptcover-makes-javascript-coverage.html) that I think could be a great start for helping resolve the the slow script problem -- if such an extension could be made for IE.
So, to reiterate my main question is what tools/processes can one use to debug/analyze a slow script dialog appearing on a user's machine? A subquestion would be, does anyone know of any JavaScript code analysis tools that could be repurposed to help in diagnosing the slow script dialog in IE, and that takes minimal deployment effort? Can an IE extension be written, in theory, that does the sort of code coverage as the Google' script cover extension does?
Thank you,
Notre
In the old times JavaScript was not used that much. Pages used to me more static. These days the PC's were less powered and it was more popular to run complex tasks on the server. JavaScript was only used for some animations.
Microsoft (my way or no way) took their time to acknowledge heavily JavaScript-ed content. (They were also fiddling with their JScript in IE8). Until IE9 they were considering that running > 5 000 000 instruction in a script is a potential mistake.
I'm not aware of any tool that retrieves the instructions count. It's a browser build in feature.
But most of the browsers retrieve the execution time of a function. I know that in every different computer, same number of instructions can take different times, but you can set a benchmark.
Run a script with 5 000 000 instructions on the machine and see how long it takes to run. Then use that time to benchmark your other JavaScript. It's not 100 % accurate but it can became close once you fiddle with it.
Since old IE developer tools are quite poor you can use some third party one. A ussage example here:
deep-tracing-of-internet-explorer
Anyway, the “A script on this page is causing your computer to run slow ...” is only a problem in IE4 - IE8. Since those browsers are obsolete, so should this question be.

WebKit's Audits tool - runs forever

I'm trying to use WebKit's audits panel to remove some unused CSS in a fairly complicated webapp I'm working on. It loads forever, and it's not a bug in WebKit because it works well on other sites. All resources have finished loading - there are no pending requests that I can see, and I think JavaScript should be idling too...
This happens both in Chrome and Safari (latest), OS X 10.7.
Any ideas?
Since recently, canary Chrome allows you to stop running audits, but the best option possible would be coming up with a publicly available test case URL that can be accessed by developers, and filing a respective bug using http://new.crbug.com (mention "DevTools" in the summary line and set the "Feature-DevTools" label if possible.)
I find that Webkit's audit runs forever when it has no errors to find. It's a bug and it's probably reported. What I usually do is just restart the browser and do another audit. That usually works. In the meantime I'm sure a fix will be out

Profiling JavaScript without crashing your browser

So tried my hand at profiling some code and I figured the easiest way to do it (at least on Firefox) was to use either console's time/timeEnd or profile/profileEnd, and I tried both.
The problem I have is with the number of runs I can do before Firefox crashes on me. Now I won't paste the code here because it's typical benchmarking code (and it's very messy), but obviously the gist of it is that it runs functions (a test is represented with a function), logging their execution time for a certain number of runs.
Now with for example, 5e4 it sorta works but I don't think it's enough to spot (very) micro optimizations, but more than that, it crashes.
So how do you profile your JavaScript? Because this way, it's barely feasible.
When I used to profile my JavaScript code I used Chrome's profiler; the JavaScript Console in the developer view gives it, and it pretty much worked for me. Have you ever tried it?
I have tried profiling a page with a lot of scripting in Firebug on FF4 and the same in Chrome (last version). Firefox crashed within a second or two, Chrome didn't seem to have problems with it. Maybe you can find something on it in the Firebug issues list?
Although not a traditional code profiler, I recommend Google's Speed Tracer:
Using Speed Tracer you are able to get a better picture of where time is being spent in your application. This includes problems caused by JavaScript parsing and execution, layout, CSS style recalculation and selector matching, DOM event handling, network resource loading, timer fires, XMLHttpRequest callbacks, painting, and more.
I think the profiler in the JavaScript Debugger (aka Venkman) is quite good. The version currently on addons.mozilla.org is not compatible with Firefox 4, but the change necessary to make it work has been committed. See https://bugzilla.mozilla.org/show_bug.cgi?id=614557 for details.
dynaTrace AJAX edition(free)- one more tool in your bag. Offers a little bit more detailed performance metrics, IMHO. They used to have it only for IE, but their new one supports FF too. Also see Steve Sounder's blog

Does the browser "cache" javascript code?

I was fine tuning a page that is heavy on jquery and stumbled across this website:
http://www.componenthouse.com/extra/jquery-analysis.html
When I click on the "Run Test" button the first time, the numbers are way higher than subsequent clicks. Is this because JS is cached by the browser? Can someone explain how this works internally? Can a user choose to not cache the JS?
External javascript files are cached and, of course, an html containing script tags can be cached too.
What you see may be a result of html caching or some browser optimization. You should try different browsers, closing and re-opening your browser and clearing the cache of the browser.
The numbers are (significantly) different for me on the second time in Firefox 3.5. OTOH, they are fairly consistent(ly slow) in IE 8. Firefox 3.5's JavaScript interpreter compiles the JS to executable code. So it does make sense that the first time is slower; the code hasn't been JITted yet.
The performance boost you're seeing is likely due to your javascript interpreter. Most newer web browsers use a JIT-compiling javascript engine so code paths taken multiple times can be optimized.
Read this blog post on how Safari's javascript engine achieved many of its speed-ups.
Whether or not JavaScript code is cached, execution performance isn't affected. What you are seeing is jQuery caching the results for the selector queries so they don't take as long on subsequent runs.

Categories