0

Got this script:

<script type="text/javascript">
var imones = [];
imones.push('example.com');
imones.push('cnn.com');
imones.push('apple.com');


var beforeloadingtime = (new Date()).getTime();
var beforeTime = [];
beforeTime[0] = beforeloadingtime;
$.each(imones, function (index, value) {
    var jsonnuorodos = "http://anyorigin.com/get?url=" + imones[index] + "&callback=?";
    $.getJSON(jsonnuorodos, function (data) {
        var iframe = $("#output")[0];
        var doc = iframe.document;
        if (iframe.contentDocument) {
            doc = iframe.contentDocument;
        } else if (iframe.contentWindow) {
            doc = iframe.contentWindow.document;
        }
        doc.open();
        doc.writeln(data.contents);
        doc.close();
        var loadingtime = (new Date()).getTime();
        beforeTime.push(loadingtime);

        var result;
        result = (beforeTime[index + 1] - beforeTime[index]) / 1000;
        console.log("result - " + result);
    });
});
</script>

In console i get these results:

result - 1.741 
result - NaN 
result - 0.86 

I am getting NaN on my 2nd result because beforeTime[index+1] value is always unidentified.

Edit: if i write console.log("index= "+[index]); console.log("index+1= "+[index+1]); i am getting:

index= 0 
index+1= 1 
index= 2
index+1= 3
index= 1
index+1= 2 

where it should have been:

index= 0 
index+1= 1 
index= 1
index+1= 2
index= 2
index+1= 3
1
  • you should consider following the rules of this community and format your javascript so it becomes readable. Commented Mar 1, 2013 at 11:22

2 Answers 2

1

maybe the reason is that you use the $.getJson and you use $.eachto create this function. That is nonsynchronous. The index=3 's response speed faster than index=2, so....

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

Comments

0

Fixed it by adding a simple for loop:

for (i=0;i<4;i++){
var result;
result = (beforeTime[i+1] - beforeTime[i]) / 1000;
}

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.