I get an error message from Firefox "Unresponsive script". This error is due to some javascript I added to my page.
I was wondering if the unresponsiveness are caused exclusively by code loops (function calling each other cyclically or endless "for loops") or there might be other causes ?
Could you help me to debug these kind of errors ?
thanks
One way to avoid this is to wrap your poor performant piece of code with a timeout like this:
setTimeout(function() {
// <YOUR TIME CONSUMING OPERATION GOES HERE>
}, 0);
This is not a bullet proof solution, but it can solve the issue in some cases.
According to the Mozzila Knoledgebase:
When JavaScript code runs for longer than a predefined amount of time, Firefox will display a dialog that says Warning: Unresponsive Script. This time is given by the settings dom.max_script_run_time and dom.max_chrome_script_run_time. Increasing the values of those settings will cause the warning to appear less often, but will defeat the purpose: to inform you of a problem with an extension or web site so you can stop the runaway script.
Furthermore:
Finding the source of the problem
To determine what script is running too long, click the Stop Script button on the warning dialog, then go to Tools | Error Console. The most recent errors in the Error Console should identify the script causing the problem.
Checking the error console should make it pretty obvious what part of your javascript is causing the issue. From there, either remove the offending piece of code or change it in such a way that it won't be as resource intensive.
EDIT: As mentioned in the comments to the author of the topic, Firebug is highly recommended for debugging problems with javascript. Jonathan Snook has a useful video on using breakpoints to debug complex pieces of javascript.
We need to follow these steps to stop script in Firefox.
Step 1
Launch Mozilla Firefox.
Step 2
Click anywhere in the address bar at the top of the Firefox window, to highlight the entire field.
Step 3
Type "about:config" (omit the quotes here and throughout) and press "Enter." A "This might void your warranty!" warning message may come up; if it does, click the "I'll be careful, I promise!" button to open the page that contains all Firefox settings.
Step 4
Click once in the "Search" box at the top of the page and type "dom.max_script_run_time". The setting is located and displayed; it has a default value of 10.
Step 5
Double-click the setting to open the Enter Integer Value window.
Step 6
Type "0" and click "OK" to set the value to zero. Firefox scripts now run indefinitely, and will not throw any script errors.
Step 7
Restart Mozilla Firefox.
Excellent solution in this question: How can I give control back (briefly) to the browser during intensive JavaScript processing?, by using the Async jQuery Plugin. I had a similar problem and solved it by changing my $.each for $.eachAsync
there could be an infinite loop somewhere in the code
start by commenting out codes to identify which section is causing it
too many loops: there might be a chance that your counter variable name clashes, causing the variable to keep resetting, causing the infinite loop.
try as much as possible to create hashes for your objects so much so that read time is O(1) and in a way caching those data
avoid using js libs as some of the methods might cause overheads. eg. .htm() vs .innerHTML
setTimeout() yes and no -- depends on how you chunkify your codes
Related
I have created an IIS MVC webpage.
Users find that if they leave it open overnight it is in some "frozen" state in the morning and it has also frozen any other tabs that might be open in the brower.
Therefore, they have to kill the whole browser window and log into my webpage again.
How can I cleanly shutdown(or put into nice state) my webpage at 10PM?
I have tried the following, which works on Chrome, but not Firefox:
setTimeout(function () { quitBox('quit') }, millisTill10);
function quitBox(cmd) {
if (cmd == 'quit') {
open(location, '_self').close();
window.close();
}
return false;
}
I am happy to leave the tab there - but put it into some kind of clean, dead state, that would not interfere with the other tabs.
I have tried to catch the error to fix it - but I have no idea what is causing it to freeze. The code below does NOT catch it:
window.onerror = function(error, url, line) {
alert('Inform please ERR:'+error+' URL:'+url+' L:'+line);
};
Fuller version:
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
var stackTrace = "Not available";
try {
stackTrace = errorObj.prototype.stack
} catch (e) {
try {
stackTrace = errorObj.stack
} catch (e) {
try {
stackTrace = errorObj.error.stack
} catch (e) {
}
}
}
alert('Please inform of Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
+ ' Column: ' + column + ' StackTrace: ' + errorObj + ' ST: ' + stackTrace);
}
Debugging a Browser Death
Rather than looking at how to "kill" the tab, it might be worth looking at why the application is dying in the first place. Firefox is a single-process browser (currently), but it has a lot of safety checks in place to keep the process running, which means that there's a pretty short list of things that can actually "kill" it.
First off, let's cross off some things that can't kill it: Plugins like Java and Flash. These run in a separate process already (if they're running at all):
So at most, if they're runaways, they'll kill themselves but the rest of the browser will still be running.
Second, you're not seeing memory warnings. Firefox is pretty good about displaying an error dialog when JavaScript consumes too much memory, so if you're not seeing that, odds are really good it's not an out-of-memory issue.
The Most Likely Causes
What that leaves is a fairly short list of possibilities:
Browser bug (unlikely, but we'll list it anyway)
Browser add-on/extension bug
Infinite loop in JavaScript
Infinite recursion in JavaScript
Not-quite-infinite-but-close-enough loop/recursion in JavaScript
Now let's cross those off.
A browser bug is unlikely, but possible. But, as a general rule when debugging, assume it's your code that's broken, not the third-party framework/tool/library around you. There are a thousand really sharp Mozilla devs working daily to kill any bugs in it, which means that anything you see failing probably has your code as a root cause.
A browser extension/add-on bug is possible, but if you're seeing this on everybody's computers, odds are good that they all have different configurations and it's not an issue with an extension/add-on. Still, it's probably worth testing your site in a fresh Firefox install and letting it sit overnight; if it isn't broken in the morning, then you have a problem with an extension/add-on.
A true infinite loop or infinite recursion is also pretty unlikely, based on your description: That would likely be readily detectable at a much earlier stage after the page has been loaded; I'd expect that at some point, the page would just suddenly go from fully responsive to fully dead — and, more importantly, the browser has an "Unresponsive script" dialog box that it would show you if it was stuck in a tight infinite loop. The fact that you're not seeing an "Unresponsive script" dialog means that the browser is still processing events, but likely processing them so slowly or rarely that it might as well be completely frozen.
Not Quite Infinite Death
More often than not, this is the root cause of "dead page" problems: You have some JavaScript that works well for a little bit of data, and takes forever with a lot of data.
For example, you might have code on the page tracking the page's behavior and inserting messages about it into an array, like this, so that the newest messages are at the top: logs.unshift(message) That code works fine if there are relatively few messages, and grinds to a halt when you get a few hundred thousand.
Given that your page is dying in the middle of the night, I'd wager dollars to donuts that you have something related to regular tracking or logging, or maybe a regular Ajax call, and when it kicks off, it performs some action that has overall O(n^2) or O(n^3) behavior — it only gets slow enough to be noticeable when there's a lot of data in it.
You can also get similar behavior by accidentally forcing reflows in the DOM. For example, we had a chunk of JavaScript some years ago that created a simple bulleted list in the UI. After it inserted each item, it would measure the height of the item to figure out where to put the next one. It worked fine for ten items — and died with a hundred, because "measure the height" really means to the browser, "Since there was a new item, we have to reflow the document to figure out all the element sizes before we can return the height." When inserting, say, the 3rd item, the browser only has to recompute the layout of the two before it. But when inserting the 1000th item, the browser has to recompute the layout of all 999 before it — not a cheap operation!
I would recommend you search through your code for things like this, because something like it is probably your root cause.
Finding the Bug
So how do you find it, especially in a large JavaScript codebase? There are three basic techniques:
Try another browser.
Divide and conquer.
Historical comparison.
Try Another Browser
Sometimes, using another browser will produce different behavior. Chrome or IE/Edge might abort the JavaScript instead of dying outright, and you might get an error message or a JavaScript console message instead of a dead browser. If you haven't at least tried letting Chrome or IE/Edge sit on the page overnight, you're potentially ignoring valuable debugging messages. (Even if your production users will never use Chrome or IE/Edge, it's at least worth testing the page in them to see if you get different output that could help you find the bug.)
Divide-and-Conquer
Let's say you still don't know what the cause is, even bringing other browsers into the picture. If that's the case, then I'd tackle it with the approach of "divide and conquer":
Remove half of the JavaScript from the page. (Find a half you can remove, and then get rid of it.)
Load the page, and wait for it to die.
Analyze the result:
If the page dies, you know the problem is still in the remaining half of the code, and not in the half you removed.
If the page doesn't die, you know the problem is in the half you removed, so put that code back, and then remove the good half of the code so you're left with only the buggy code in the page.
Repeat steps 1-3, cutting the remaining JavaScript in half each time, until you've isolated the bug.
Since it takes a long time for your page to die, this may make for a long debugging exercise. But the divide-and-conquer technique will find the bug, and it will find it faster than you think: Even if you have a million lines of JavaScript (and I'll bet you have far less), and you have to wait overnight after cutting it in half each time, it will still take you only twenty days to find the exact line of code with the bug. (The base-2 logarithm of 1,000,000 is approximately 20.)
Historical Analysis
One more useful technique: If you have version control (CVS, SVN, Git, Mercurial, etc.) for your source code, you may want to consider testing an older, historical copy of the code to see if it has the same bug. (Did it fail a year ago? Six months ago? Two years ago?) If you can eventually rewind time to before the bug was added, you can see what the actual change was that caused it, and you may not have to hunt through the code arbitrarily in search of it.
Conclusion
In short, while you can possibly put a band-aid on the page to make it fail gracefully — and that might be a reasonable short-term fix while you're searching for the actual cause — there's still very likely a lot more you can do to find the bug and fix it for real.
I've never seen a bug I couldn't eventually find and fix, and you shouldn't give up either.
Addendum:
I suppose for the sake of completeness in my answer, the simple code below could be a suitable "kill the page" band-aid for the short term. This just blanks out the page if a user leaves it sitting for eight hours:
<script type='text/javascript'><!--
setTimeout(function() {
document.location = 'about:blank';
}, 1000 * 60 * 60 * 8); // Maximum of 8 hours, counted in milliseconds
--></script>
Compatibility: This works on pretty much every browser with JavaScript, and should work all the way back to early versions of IE and Netscape from the '90s.
But if you use this code at all, don't leave it in there very long. It's not a good idea. You should find — and fix! — the bug instead.
If the tab was opened by JavaScript, then you may close it with JavaScript.
If the tab was NOT opened by JavaScript, then you may NOT close it with JavaScript.
You CAN configure FireFox to allow tabs to be closed by JavaScript by navigating to about:config in the URL bar and setting dom.allow_scripts_to_close_windows to true. However, this will have to be configured on a machine-by-machine basis (and opens up the possibility of other websites closing the tab via JavaScript).
So:
Open the tab via JavaScript so that it can then be closed by JavaScript
or
Change a FireFox setting so that JavaScript can close a tab.
PS. I'd also recommend taking a look at https://developers.google.com/web/tools/chrome-devtools/memory-problems/ to try to help identify memory leaks (if the application has a memory leak) or having the web app ping the server every minute for logging purposes (if the application is breaking at an unknown time at the same time every night).
As was mentioned in other comments you don't need to find how to close, you need how to avoid "freezing".
I suggest:
Collect statistic what browser/browsers fall
Collect metrics from browser that fail you can use window.performance and send logs to the server in timeout (I haven't tried, timeout can freeze before you have logs you need)
I have a load of code, and I think much of it is deprecated with numerous methods that are never called. I would like to know which methods in this code will never be called, either as a result of button clicks or via other methods. I could go through and comment out the suspicious methods one-by-one and test the code, but is there a better way?
I am using Visual Studio 2012, and I have tried using JS Lint but that doesn't seem to tell me what I want to know. I really like the Code Analysis for C# and SQL that VS2012 does, but it doesn't do this for Javascript. What should I use?
Open your JS file as the script in a webpage in Chrome. Just surround your JS with an html and script tag:
<html><script>
var mycode = goeshere();
</script></html>
Once you open it in chrome, right click anywhere on the page and click 'Inspect Element'.
Alternatively you can just press CTRL+SHIFT+J to bring up the console.
Once the pane opens, click on the 'Profiles' tab.
Select "Collect JavaScript CPU Profile", and follow the steps to run it.
This will give you timing counts per function call. Try to work through as much of the functionality as you can, then once you are finished look at the function timing counts. Any call with 0 time probably wasn't called. This should at least give you a starting point.
I developed a .htm document with an in-built script for javascript to run a program. In google chrome, the program works fine, but I got a beta test complaint that it didn't work on firefox 14.01 or opera. On testing with firefox 14.01, I can confirm it doesn't work (I assumed opera to be the same). I cannot insist the audience upgrade their browsers, as this is supposed to be widely compatible.
Doing a little tracing of the issue, I installed Firebug, which, on clicking the Javascript button to generate a coordinate the first time, it worked (clearly showing the function is defined and exists), but the second time, Firebug complained that:
"ReferenceError: GenerateCoord is not defined".
This wouldn't be so ironic if it only did this after generating an (encrypted) coordinate (thus calling GenerateCoord that is supposedly 'undefined').
If one looks in the code, one can clearly see that the function GenerateCoord is clearly defined before it is called. I would say firefox has an 'onclick' issue, but then it begs the question why did it work the first time I clicked it (calling GenerateCoord via 'onclick') but not the second?
Reloading the file allows the button to work the first time, and the first time only. I am baffled as to how firefox can call a function one time that it then says is undefined the next. Am I missing something here?
Javascript and HTML code can be viewed here:
http://pastebin.com/4qykTfEW
-
How do I solve the problem, and is there an easier solution than re-writing the code to avoid onclick (that seems to work in certain circumstances but not others)?
The problem is that using document.write overwrites the entire HTML page, thus inadvertently removing the GenerateCoord script. I'd suggest appending the link to the document (in ShowTarget) rather than attempting to re-write it.
For example, have a container element where the link should be:
<div id="links_container"></div>
Then to append the links, use:
document.getElementById('links_container').innerHTML = Link;
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
I have been using Eclipse for some weeks now and I start getting used to it.
However, one thing really annoys me:
When editing JavaScript (I didn't try any other language yet), the editor window keeps jumping to the start of the document I am editing.
This mostly happens when the code currently contains syntax errors and mostly while / after deleting lines.
Especially constructs like { = and sometimes unterminated strings / comments seem to cause this problem.
When it happens, only the view scrolls to the top of the document - the cursor stays where it was before the "jump" occurred.
Anyone having an idea on how to fix this?
I believe the problem described above is related to this bug:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=318095
The work around is to disable the "Link with Editor" option from the Project Explorer. Which is to say make sure the icon with two arrows facing in opposite directions at the top of the file tree is not enabled. Disabling this option resolved the issue for me.
Looks like a problem with the implementation of the JavaScript editor. Most probably the jump occurs when the JavaScript-Parser is not able to parse your document and throws an exception. You might consider to report a bug to the eclipse project (maybe there is already such a report?).
As a workaround you might consider to adapt your way of typing the code a bit. Try to write the code in a way that does not confuse the parser (for example it might help to immediately close a newly created comment and THEN write the content instead of open the comment, write the content and finally close the commend). Same for strings, blocks ...
I am having the same problem. I had this line of code in my file and I could consistently reproduce the issue:
$.preload(preloadImages
, {
base:assetsUrl+'b/images/',
ext:'.png'
});
I changed it to the following and I no longer have the problem.
$.preload(preloadImages, {
base:assetsUrl+'b/images/',
ext:'.png'
});
I get this Phenomenon, when i'm editing in a Java-Class while still residing in a Debug-Process. The Debugger recognises the Change and reevaluates the Code and jumps back in order to be able to reexecute only the changed Code.
Hii i got solution goto
Window->Preferences->search autosave
and disble it and hit apply and close button.
this worked for me !