Reputation: 35331
Consider the following silly example:
<!doctype html>
<meta charset="utf-8">
<title>dumb snippet</title>
<script>
var i = 0;
while (i < 100) {
console.log(i);
debugger;
i += 1;
}
</script>
If I run this code using Google Chrome's DevTools, the debugger dutifully stops execution at the debugger
statement, but I have not found any way to immediately abort (and restart) the script. AFAICT, pressing Ctrl-R
or even Shift-Ctrl-R
, rather than reloading the page, merely causes the execution to continue.
The only recourse I've found is obvious, but unnecessarily inconvenient: kill the tab/window altogether, and open up a new one.
Does the Google Chrome DevTools provide some way to immediately abort a script that is stopped at a debugger
statement?
(If the answer happens to be "no", please do not post work-arounds. I can think of plenty of them, e.g. holding F-8 until the loop exits, although this won't work, of course, if the loop turns out to be an infinite loop. In any case, here I am only interested in whether there is an "official" way to abort and restart such a script.)
Upvotes: 2
Views: 1556
Reputation: 40106
You can do it, but you must prepare your code first.
Instructions for halting script execution in Google Chrome Dev Tools:
(1) Create a global variable:
var devquit=0;
$(document).ready({
//the rest of your code
(2) Any place where you may wish to quit, insert a test of this variable:
//Lotsa code
if (devquit > 0) return false;
(3) Pause execution of script on-or-before the above test line(s)
(4) Switch to console
(5) Type:
> devquit
0
> devquit=1 <=== only this line is necessary
> devquit
1
(6) Continue script execution. Script will return false
when it executes the test from step (2) above
Notes:
(A) This trick works with global variables and objects, but it will not work with local variables.
(B) So, you can still use this trick with already-running code IF you have either a global variable or an object that will return false if it has a given value.
(C) In a pinch, you can also delete an element from the DOM (on the elements tab) that will cause a javascript error. For example, suppose you have code var cartype = $('#cartype').val();
If you delete the element with ID=cartype
before that line of code, then the js will break on that line. However, the element will still be missing when you try to re-run the code. The trick described above allows you to run and re-run the code ad infinitum.
More notes:
(a) Insert breakpoint into code: just type debugger;
on a line by itself. If DevTools is open, the script will jump into debugger at that point. If DevTools not open, code will ignore statement.
(b) Want to avoid jumping into the jQuery library when debugging code? Blackbox it. See blackbox instructions for Chrome - or - for Firefox
References:
Javascript Debugging line by line using Google Chrome
Is it possible to change javascript variable values while debugging in Google Chrome?
Upvotes: 1