How to use a global variable counter? [duplicate]

1

Click to test!

My goal is for the count variable to get the value that will accumulate in the arrayVec1 function, but instead I always get the result 0. Can anyone tell me how I can pass the value out of the function and assign it to the global variable?

Code:

//cout if exits
var count=0;

var vec = new Array(); 
var vec1= new Array();
var tag1="wedding ball evening gown";
arrayVec();
 

function arrayVec() {
$.getJSON("http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?",
        function (jd) {            
            for (var i = 0; i < jd.items.length; i++) {
                vec.push(jd.items[i]);  
            }          
            arrayVec1();              
        });
} 

function arrayVec1() {
 for (var i = 0; i < vec.length; i++) {         
         $.getJSON('http://www.flickr.com/services/feeds/photos_public.gne?tags='+"ball"+'&format=json&jsoncallback=?',
        	function (jd) {  
            for (var i = 0; i < jd.items.length; i++) {
                  if (tag1 ===  jd.items[i].tags) {
                    count++;                   
                   }
            }                   
        	                 
        });
     
    }	      
} 

alert(count);
    
asked by anonymous 26.05.2015 / 21:44

1 answer

2

Ana, the problem is that $.getJSON is asynchronous.

The value of count will be changed as you expect but after of your alert . That is, $.getJSON will run in parallel, asynchronous, and will respond after script has called the alert.

You need to use count within this $.getJSON callback. You can for example test:

setTimeout(function(){
    alert(count);
}, 1000);

and you will see that this 1 second wait will already show the count with the new value.

The count will have the final value on the line following this loop:

for (var i = 0; i < jd.items.length; i++) {

If you want, you can call a function after that loop. Just as it would work to put alert(count); there, within that callback.

Example: link

    
26.05.2015 / 22:19