I'm trying to debug a bunch of functions that redirect the user. I want to "kill" the script while it's running to to read the output of console.log(). I can't just use a simple return because there are many functions that work together.
-
"many functions that work together" conveys no useful sense here. How are they loaded? Are they due at set intervals? Are they asynchronously loaded? Are they event handlers?ZJR– ZJR2012-03-12 02:22:13 +00:00Commented Mar 12, 2012 at 2:22
3 Answers
Set a breakpoint at the spot in your code where you want to pause. If you add a debugger statement in your code browsers that support it will automatically stop at that point and open the debugger (actually I think some browsers (Chrome?) may ignore the statement unless you already have the console/dev tools open, but obviously you can just start with the dev tools open if necessary).
1 Comment
console not existing unless the console is open.There are a few options, not all of them applicable to your case:
- Throw an exception; that will stop the function and any caller function as well;
- Use an
alert(), as ismaelga suggested; - Set a breakpoint, as nnnnnn suggested; you can either use the
debuggerkeyword or use your browser´s GUI if present; - Redefine
console.logto an empty function; this way nothing will be logged from then on, so you can read what was logged so far without interference.
Some situations where the options will not be possible:
- If your code is responding to events, or using things like
setInterval, even if the "main loop" stops other code can still run and log stuff; - The alert window may make difficult to see the log, depending on how obtrusive it is for your browser;
- There's no suitable debugger, or you can't install one;
- Some functions have stored a local copy of
console.log, so redefining it won't affect them.
Of all option, I'd sugest the 4th, since you can read your logs calmly without "breaking" the page. If you want to "filter" the logs, you can also have some functions call the "correct" log (a saved copy of console.log), while the rest calling the "fake" one (the one you redefined).
Comments
Declare a global variable that is outside of any function, and add code within each function or long-running loop that checks the value of that variable and only proceeds if the value is set a certain way. This way the variable serves as a semaphore and you can change its value from anywhere and terminate all processing in accordance with its value.
For example, a simple Boolean variable called stopProcessing that is initialized as false but can be set to true to let all functions know to return and all loops to break ASAP.