How to use a global variable counter?

Asked

Viewed 414 times

1

Click to test!

My goal is that the Count variable gets the value that will accumulate in the arrayVec1 function, but instead I always get the result 0. Can someone tell me how I can pass the value out of the function and assign 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);

  • Possible duplicate: http://answall.com/q/60852/129

  • Possible duplicate also: http://answall.com/q/58566/129

1 answer

2


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

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

You need to use Count inside that callback of $.getJSON. You can for example test:

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

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

The count will have the end value on the line after this loop:

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

If you want you can call a function after that loop. In the same way it would work to put the alert(count); there, inside that callback.

Example: http://fiddle.jshell.net/d4h0ykj9/2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.