How do you interrupt JS in browser? - javascript

What is the equivalent of pressing Ctrl+C in console, for Chrome and Firefox? While implementing various algorithms I often write some buggy (while) loop, in Javascript, that doesn't exit, makes the browser freeze. Reloading doesn't work, clicking little X for closing the tab doesn't do anything, and in a while (literally) I'm outta memory, system is swapping, and I'm leaving for a coffee break.

In Chrome, you can hit Shift+ESC (or right-click the title bar and open the Chrome task manager) and kill the process associated with the hung tab. This will work in cases where closing the tab would not.
The caveat is, sometimes Chrome will streamline several tabs into one process, and this will kill all the tabs associated with the process.
Another approach you can take to avoid while loops hanging the browser is to write code like this (you can take it out after testing):
var maxIterations = 100000;
while (foo) {
if (!maxIterations--) throw new Error('Max iterations hit, aborting.');
// do stuff
}
Right-click in Chrome's task manager and select the item on the bottom of the context menu to reveal a strange easter egg.

There is no such thing as a Ctrl + C for JavaScript. The browsers that executes JavaScript are usually protective of themselves. If any JavaScript hangs, they'll throw a dialog asking if the user wants to stop the JavaScript.
The timeout duration can usually be found in the browser's settings. You can find how to do it for FireFox here: http://kb.mozillazine.org/Dom.max_script_run_time

From what little insight I have into your ways of working, how I would proceed is:
Only execute the script on an event like button click. This would prevent script running onload
Chrome allows you to set break points in your js code in the scripts tab of developer tools

There is no real "interrupter" for running Javascript code in a browser. ECMAscript gets executed in the so called "UI thread", which means that all rendering stuff happens in the same queue that ECMAscript code gets executed.
That in turn means, an infinite loop in ECMAscript automatically hangs the whole browsers interaction.
The only way to avoid that is to write clear, clean code. If it happens anyway, most browsers realize that the UI thread is busy for too long and asks the user if he wants to cancel the running javascript processes. If you don't want to wait for that, your only choice is to kill the whole browser / tab process.
However, if you are aware that some part of your script does possibly cause an infinite loop, you can either set breakpoints manually in some sort of developer tools or you can insert the debugger; keyword directly into your script. That causes the javascript interpreter to halt at the current line and you have a chance to analyse the next code (while conditions for instance) and cancel the execution if it looks bad.

Related

How to make debugger break every time execution invokes a certain script file in Edge/Chrome debugger?

I am debugging a Typescript web app, and I've never done web dev before. The project consists of multiple script files, multiple libraries.
When I execute the application in the debugger, I only care what goes on in one file and one file only (let's call it my_script.ts).
When I step through functions, I have to go through libraries as well, and it's time-consuming.
Is it possible to set some kind of global break point on the whole my_script.ts file so that every time execution returns from some foo_lib.js or foo_lib.ts back to my_script.ts the code execution halts regardless of where in my_script.ts we end up?
At the same time, once I am inside my_script.ts and resume the execution, I don't want it to break on every single line of my_script.ts.
I.e., I am looking for a way to invoke a breakpoint for foo.js=>my_script.ts transitions only so that I could just hit continue when I end up in an outside library and return to my_script.ts instantly.
UPD: If there is an extension that can help me, I'll take that too!
From debugger on MDN:
function potentiallyBuggyCode() {
debugger;
// do potentially buggy stuff to examine, step through, etc.
}
When the debugger is invoked, execution is paused at the debugger statement. It is like a breakpoint in the script source.
Other than that, you may need to rely on the breakpoint features of the browser you are using to debug. Chrome offers function breakpoints "when you want to pause whenever a specific function is called", and you can further set up line of code breakpoints which you can then disable after your code is initialized.
If manually disabling the breakpoints is too difficult or cumbersome, you can also set conditional breakpoints to narrowly specify the conditions where you break, including a manual boolean field you manage in your library.

Is there is any way to call a function when an infinite loop or browsser hangs in javascript?

hi i m working a project which have huge javascript code sometimes javascript code executes automaticaly and hangs browser with message "kill this page" in chrome is there is any way to track the error .like calling calling a function when infinite loop arrives or browsser hangs like that .please give me some suggestion about debugging javascript code plz.
There is no way of doing what you wish inside javascript.
However you can use a tool like DynaTrace Ajax Edition to trace cpu usage in the browser to identify what is happening.
Infinite loop can be caused in many different bad programming logic, and there is no reliable logic to detect in every case. So I highly doubt if any programming language or IDE would offer any reliable infinite loop detection.
What you saw was basically a runtime detection based on how long script execution has taken before the browser could update and refresh the UI.
Sometimes this kind of long running JavaScript could be caused by infinite loop, but many times they are just big loops or loops that perform too much work that makes UI unresponsive.
Because JavaScript is not multi-thread, therefore to avoid the later case above, you could consider breaking the loops into small units of work, once a unit is finished, don't run the next unit, but instead call the next unit of work with setTimeout with a small time delay (such as 250ms). This would give the browser a chance to breath and update UI, and unmark your script as "long-running" script.
You may also use logging such as Firebug Logging to log the loops with enough values that help you find out if those loops are indeed infinite loops.

Is there a way to pause a stuck script in the chrome debugger?

Occasionally, while programming JavaScript, I will make a bone headed mistake and can get the page stuck in an infinite loop while it is loading. I typically will use Chrome for this and, when I get in this state, I cannot do anything with the javascript developer tools. What I would really like is a break command similar to what can be done within Visual Studio's debugger that will pause the interpreter and display the current line being executed along with the call stack. Is there any such functionality available.
As an alternative to this, I would be handy to set break points in the code. Regardless, I need some way to interrupt the process so that I can determine the cause of the lock-up.
you can add a debugger; statement somewhere in your code where you want to break execution and continue stepping from there on with the Step Next, Step Over, etc

Maximum execution time for JavaScript

I know both ie and firefox have limits for javascript execution (Source 1, Source 2). Based on number of statements executed, I heard it was 5 million somewhere in IE and based on number of seconds in firefox: it's 10 seconds by default for my version.
The thing I don't get is what cases will go over these limits:
I'm sure a giant loop will go over the limit for execution time
But will an event hander go over the limit, if itself it's execution time is under the limit but if it occurs multiple times?
Example:
Lets say I have a timer on my page, that executes some javascript every 20 seconds. The execution time for the timer handler is 1 second. Does firefox and ie treat each call of the timer function seperatly, so it never goes over the limit, or is it that firefox/ie adds up the time of each call so after the handler finishes, so after 200 seconds on my site (with the timer called 10 times) an error occurs even though the timer handler itself is only 1 second long?
The following article by Nicholas C. Zakas discusses how and when different browsers interrupt long running JavaScript code:
What determines that a script is long-running?
Breaking long processing code into small chunks and launching them with timers is in fact one way to get around this problem. The following Stack Overflow post suggests a method to tackle this:
Show javascript execution progress
On the other hand, web workers would be more suited for long running processing, since their execution happens in a separate process, and therefore does not block the UI thread:
Mozilla Dev Center: Using web workers
John Resig: Computing with JavaScript Web Workers
Nicholas C. Zakas: Experimenting with web workers
However web workers are not supported in Internet Explorer yet, and they would not have access to the DOM.
The event handler is considered a new execution context - the time limit is reset.
If you need to do even more computation, take a look at WebWorkers.
I too stuck in this kind of JS error. I also get the solution, unfortunately only for IE, which tells to edit the registry (regedit command) and update the number of JS commands to allow. Read more here http://support.microsoft.com/?kbid=175500.
But this doesn't seems to be a good solution to me bcoz if you are developing a web application you can not ask every user to use only IE and update his system registry.
As a workaround: If your data to process at client end is really large then you can put some manual delays between fix set of events processing. For ex. If there are 100 events of any task you want to process then you can break them in to 10 sets of 100 and process each of them in say 100ms. To know how to do that follow below link:
http://www.nczonline.net/blog/2009/01/13/speed-up-your-javascript-part-1/

IE does not render changes while javascript script is running

I have a rather long running javascript code which adds a new "div" element to the document. It looks like in IE this change is being rendered only after the script is finished, which is not the case in FF.
Any idea how to make it work ? This script is actually supposed to run forever, kind of "main loop".
I would avoid using a persistent, ever-running script. If you need things to happen on a recurring schedule, periodically, then use Window.SetTimout/SetInterval. Otherwise, use events. There are numerous JS frameworks out there, such as Mootools, that make it easy to implement you're own custom events, which should eliminate the need for a "main loop".
http://mootools.net/
Don't use a script that constantly runs, JavaScript is not meant to be used like that. Use event-based code or scheduler-based code. I'm pretty sure if you have a constantly running script you will trigger a "some scripts on this page are taking an abnormally long amount of time to run" type of popup from some browsers. It should not be expected behavior.
This script is actually supposed to run forever, kind of "main loop".
You can't do that in JavaScript. While you keep control of the thread of execution, the browser can't do anything, like check for clicks. In this state the browser is unresponsive and can appear to have crashed. Eventually most browsers will pop up a warning saying the script isn't playing nice, and give the user a button to click to unceremoniously kill it off.
Instead, you must return control to the browser as normal and ask it to call you back a bit later by using window.setTimeout(function, delay) for a one-off or window.setInterval(function, period) to have it keep calling back every so often. Any state you want to maintain over calls will have to be stored in global or instance variables.
The reason for this behavior is the manner in which Internet Explorer re-paint the window on DOM changes; in other words it is due to reflow.
Unless I'm mistaken, IE will queue the reflow tasks, and will act on them when the script thread has finished executing. If you write code to never halt the thread, reflow will never happen and you will never visualize the changes in DOM.
The alternative method that others have suggested - using window.setTimeout() and window.setInterval() is viable and will help in resolving the problem due to brief pauses available to the browser to act on the reflow tasks.
You will find this related SO question on when reflow occurs to be useful.

Categories

Resources