brandizzi
brandizzi

Reputation: 27100

How to only stop at a breakpoint after some line was executed?

Frequently, I want to pause at a specific line while debugging, but only after another line was executed. Often, this JavaScript code was machine-generated (for example, by JSP or PHP), or should be built (e.g. by Grunt), which can be a bit annoying to do every time I want to add a breakpoint. How to stop at a specific line in this case?

For example, I have two functions, f_a() and f_b() that are called this way:

for (var i = 0; i < 1000; i++) {
  f_a();
}

f_b();
f_a();

(Running example)

I want to add a breakpoint inside f_a(), but only stop at this function after f_b() is called. How to do that?

Upvotes: 1

Views: 359

Answers (2)

Joonas89
Joonas89

Reputation: 259

You can also write debugger; in your code, and the browser dev tools will stop on that code line. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger

Upvotes: 1

brandizzi
brandizzi

Reputation: 27100

We can do the following:

  1. Add a breakpoint to f_b().
  2. Make this breakpoint conditional. As the condition, set a variable (let us say, pause_at_f_a) to true. We do not want to pause inside f_b(), so we use the coma operator to return false. The condition is then

    pause_at_f_a = true, false
    

    Adding conditional breakpoint to like that should enable other breakpoint.

  3. Add a breakpoint to f_a(). The condition of this breakpoint should be the paused_at_f_a variable.

    Check for set variable on the breakpoint that should pause.

A possible annoyance is that the breakpoint will stay enabled after we check whatever we want to check. That's why I use yet another step:

  1. Instead of merely checking if the variable is true, unset it as well if it is true, use this condition:

    pause_at_f_a ? (pause_at_f_a = false, true) : false
    

The conditional can be anything. One can use counters as well. The core of the trick is to use a breakpoint to set variables. Here is the result:

A debugging session with the trick.

Upvotes: 2

Related Questions