2

I have code like this:

for(var hour = -1; hour > -24; hour--)
   $.getJSON(url + hour, function(data) {
      //...
   });
}

I need to use the hour variable in my getJSON function. But it goes through the for loop first. It does hour = -1, -2, -3... etc.

Then finally it does $.getJSON(url + -24). I want it to $.getJSON(url + -1), -2, etc and use that variable still inside the function.

1
  • It is actually making each call, but it does it asynchronously. You, apparently, want the processing to happen synchronously, which indicates that Javascript/AJAX may not be the best solution to your problem. Commented Jun 11, 2013 at 20:31

2 Answers 2

3

I would use a recursive callback function like

function recurseJSON(hour) {
    if (hour < -24){
        return;
    }
    $.getJSON(url + hour, function (data) {
        //...
        recurseJSON(hour-1);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

2

The problem is that the $.getJSON method is asynchronous. Your code doesn't wait until the for loop is over to make the $.getJSON calls; instead your code continues past the call before it has finished.

A way to fix this is changing the $.getJSON call to an $.ajax call like this:

$.ajax(
    url:url + hour,
    async:false,
    dataType:'json',
    success:function(data) {
        //...
    }
});

$.ajax allows for adding async:false in there to make the ajax call synchronous.

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.