0

I'm trying to pass a variable to a function as fined in several documentations, and even here on StackOverflow, but when I define it... it doesn't work... if I set the variable to true prior to the function it works fine. And it is getting to the part where it should be defining proceed as true as it's alerting me... but it doesn't change the var

I realize this timeout does nothing to delay the execution of each loop, never mind that. :P Haven't removed it.

var rand = function() {
    return Math.random().toString(36).substr(2);
};

$(function(){
    $('.lhc').each(function() {
        var rawlink = $(this).attr("href");
        var link = encodeURIComponent( rawlink );
        var token = rand();
        var proceed;
        $.get( "lhc/link.php?link=" + link + "&a=c", function( data ) {
            if ( data == 1 ) {
                proceed = true;
                alert('true');
            } else {
                proceed = false;
            }
        });
        if ( proceed ) {
            $(this).after( " <span style='font-size:xx-small;'>( Hits: <span id='" + token + "'></span> )</span>" );
                setTimeout($.get( "lhc/link.php?link=" + link + "&a=q", function( data ) {
                    $('#' + token).html(data);
                }), 3000);
            $(this).attr( "href", "lhc/link.php?link=" + link + "&a=g" );
        }

    });
});
Nick
  • 1,417
  • 1
  • 14
  • 21
WASasquatch
  • 1,044
  • 3
  • 11
  • 19

2 Answers2

1

The $.get is calls AJAX, the variable proceed will change when AJAX response, but the loop will not wait for ajax response, because the the ajax default setting async: true

More Info

Community
  • 1
  • 1
Girish
  • 11,907
  • 3
  • 34
  • 51
0

timeout needs a function to be called -

setTimeout(function(){
  yourFunction(token,link);
}, 3000);

function yourFunction(token,link){
  $.get( "lhc/link.php?link=" + link + "&a=q", function( data ) {
                    $('#' + token).html(data); 
  });
}
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • Thanks for your input. Yeah I figured it out, throw $.get into the proceed variable and have it return true, or false. Scopes at hand. Good read. – WASasquatch Mar 26 '14 at 06:11