javascript - How to keep index straight when ajax request are async and not finishing in order -


i interacting vimeo oembed api getting videos. context have multiple events each set of videos. keeping page load times down getting first set of videos rather loading of them.

this function takes 4 parameters , gets video, returning result calling function loading. videourl http://www.vimeo.com/videoid, index based on .each in calling function iterating through available id's, count total number of videos called , callback handles data getting calling function. once function done calls showfirstvideo shows video first thumbnail generating.

the issue having because ajax calls async, indexeq var jumps around. instead of: 0, 1, 2, 3, 4 ... 1,6,3,0...

i need indexeq increment in order @ end can run showfirstvideo function @ appropriate time.

function loadvideo(videourl, index, vidscount, callback) {     var indexeq = index;     $.when(         $.ajax({             type : "get",             url : "http://www.vimeo.com/api/oembed.json",             data : {"url" : videourl },             datatype : "jsonp",             success : function(result) {                 index++;                 callback(result);             },             error : function(error) {                 var s = "";                 $.each(error, function(name, value){                     s += name + ": " + value + "\n";                 });             }         })     ).done(function(){         console.log(indexeq);         if(indexeq === vidscount){             $('.video-thumbs').velocity("fadein");             $('.past-concert-loader').velocity("fadeout");             showfirstvideo();              // reset index, when have call function again.             console.log("trigger indexeq 1");             indexeq = 1;         }     }); } 

the $.each calls function:

$.each(vids, function(i, val){         var videourl = 'http://www.vimeo.com/'+val+'';         loadvideo(videourl, i, vidslength, function(result){             $('.video-thumbs').append('<div class="col-xs-6 col-sm-3 video-thumb video-'+i+'" data-video-id="'+ result.video_id +'"><img src="'+ result.thumbnail_url +'" alt="'+ result.title +'" class="img-responsive"></div>');         });     }); 

you can declare indexeq global variable outside function. , increment indexeq value every time ajax called. ensure values in sequence.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -