1

I have a javascript file called pendingAjaxCallsCounter.js with a variable "var pendingAjaxCalls" which is incremented/decremented when various methods in the js file are called.

Separately, I have created an automated testing app which checks that the pendingAjaxCalls has a value of 0 before interacting with any page. I'm wondering, if a given page, were to import the js file multiple times; multiple statements, how would that affect the value of my variable "var pendingAjaxCalls"?

1
  • As of 1/28/10 I can say that all of the answers were really helpful in improving my understand of javascript, and arriving at a solution for this problem. Thanks everyone. Commented Jan 29, 2010 at 0:36

3 Answers 3

3

The script would be run each time it was included, but make sure that you don't redefine the pendingAjaxCalls variable each time. i.e. Check it's defined before declaring it with something like:

if(!pendingAjaxCalls)
  var pendingAjaxCalls=0;

/* code happens here */

pendingAjaxCalls++;
Sign up to request clarification or add additional context in comments.

2 Comments

This lead me to my solution. Thanks. I ended up with a statement like this: if(pendingAjaxCalls == null){ var pendingAjaxCalls = 0; } /* .... / / code that incremenets/decrements pendingAjaxCalls */ Based on what I read in a javascript book, this if statement will test if the variable pendingAjaxCalls is undefined or null based on javascript type coercion that happens in the "==". This way if the variable has already been "spit out" somewhere else in the code I won't end up messing with it.
Yes - and if(!pendingAjaxCalls) is equivalent to if(pendingAjaxCalls == null), since 0 == null == false. But I'm glad it helped!
1

Each time you include a script using a script tag, the browser will download the file and evaluate it. Each time you include a JavaScript file the contents will be evaluated.

Comments

1

If the actual call to the function that increments your variable is being inserted more than once, you could be incrememting it multiple times.

On the other hand, if only the function that increments it is being inserted multiple times (not the function call), then JavaScript will use the most recently defined version of this function. So it shouldn't be incremented extra times in that case.

In other words, if you insert the same function twice but only call it once, you don't have to worry about "both copies" of the function being called, since one copy effectively overwrites the other.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.