Synchronization with JavaScript
Sup guys !
I'm currently have some problems about the synchronization with JavaScript. It's about a refresh. When it reach 10 second i refresh an array.
var curD = new Date();
if((curD.getTime() / 1000) - dMList[i].startTime > dMList[i].refreshTime)
{
dMList[i].elem = new Array();
RSSDropMenuConstructor(dMList[i]);
dMList[i].startTime = curD.getTime() / 1000;
}
sendResponse({ getdropMenuFields: dMList[i] }); // Send the appropiate dropMenu
Function RSS
function RSSDropMenuConstructor(dMObject)
{
jQuery.getFeed({
url: dMObject.rssLink,
success: function(feed) {
for(var i = 0; i < feed.items.length && i < dMObject.maxItem; i++) {
var item = feed.items[i];
field = new Object();
field.name = 'text';
field.value = item.title;
dMObject.elem.push(field);
field = new Object();
field.name = 'weblink';
开发者_Go百科 field.value = item.link;
dMObject.elem.push(field);
field = new Object();
field.name = 'icon';
field.value = 'http://mediacdn.disqus.com/1305270873/images/embed/bullet-feed.png';
dMObject.elem.push(field);
}
dMList.push(dMObject);
}
});
So the RSSDropMenuConstructor will construct the dMList[i].elem, but the problem is that then "SendReponse" don't wait the end of the function.
So what it happend, when it refresh i received an empty array because the array is not yet initialized... Somebody have an idea how i can synchronize this ?
You need to wait for the feed to come back from the server before calling sendResponse(). Place the call to sendResponse() in the callback function (that is, function(feed){...}).
Because AJAX is asynchronous, Javascript will continue to execute your code, even while a request to the server is pending. The callback, on the other hand, does not execute until the server responds.
Put the sendReponse() function inside the if statement. That way it will execute when the rest of the code inside that block is executing.
精彩评论