jQuery - Keeping an asynchronous function from running more than once simultaneously
I have an asynchronous function that is triggered by an "onmouseover" that sends a request for children nodes to a list and displays them. Setting it to be synchronous prevents this, but as far as I know, it needs to be asynchronous in order to display a loading icon in Chrome and IE. The problem is that if you mouseover more than once while the function is still executing, it loads the children multiple times. What I am having trouble with is preventing the function from running more than once at a time, to prevent the children n开发者_JS百科odes from being loaded more than once.
Thanks in advance!
My ajax call (jQuery instead of $ because I am running in noconflict mode):
var ul = "#ul_" + categoryId;
var ifUlExists = jQuery(ul);
// Only if UL not already loaded
if (ifUlExists.length == 0) {
jQuery.ajax({
type: 'POST',
url: '/adminajax/add_kids',
data: {
categoryId: categoryId
},
beforeSend:function(){
// Toggle +/- icon
jQuery(expandIcon).addClass("loading");
},
success:function(resp){
var kids = resp;
// If there are kids returned by the query
if (kids){
var container = "#c_"+categoryId;
jQuery(kids).insertAfter(jQuery(container));
jQuery(ul).slideDown("slow");
}
})};
} else {
jQuery(expandIcon).addClass("collapse");
jQuery(ul).slideDown("slow");
}
It's not going to run "simultaneously"; a better word would be "concurrently". Anyway just set a flag:
if (ifUlExists.length === 0 && !$('body').data('loadingUl')) {
$('body').data('loadingUl', true);
// the rest of your code
}
Using the "body" element data is just one of a zillion ways to do it, but I kind-of like it because $('body')
is made pretty cheap by jQuery. You could keep the flag anywhere of course.
A flag is one option:
var running = false;
$(selector).mouseover(function() {
if(!running) {
running = true;
callAsyncFunction();
}
});
and in the callback of the Ajax request, set running = false
again.
If you want to do that for several elements, you can use the data()
function of that element as @Pointy describes in his answer.
精彩评论