Wait for function to finish before starting again
Good Morning,
I am trying to call the same function everytime the user presses a button. Here is what happens at the moment..
User clicks button -> Calls function -> function takes 1000ms+ to finish (due to animation with jQuery and AJAX calls)
What I want to happen is every time the user presses the button it adds the fun开发者_如何学JAVAction to the queue, waits for the previous call to finish, and then starts..
Is this possible?
Sorry if my explanation is a bit confusing..
Thanks Matthew
Since Functions are objects they can store properties. You can have your function increment a 'queue' property on itself every time its called (button pressed) and then at the end of the function execution, check if the queue property of itself is > 0, and if so, decrement the queue property by one and call itself again using setTimeout
.
You could add a callback function to the one that makes the animation, once the animation finishes the callback it's called so you can do what you want.
Here follows an example from the jquery docs:
$('#clickme').click(function() {
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Put your code here, so it will be executed once the animation completes
});
});
P.S.: Morning? It's almost midnight ;D
You could keep track of a global queue/array where you add to the queue each time the user presses the button, then you'll want a callback in your function (such as in the success
callback for jQuery) that does the work to check the queue and call the next function on the queue.
I recently had to do this in my own application. The best suggestion I have for you is (assuming you already have your AJAX calls inside of a JavaScript function) to pass a callback function parameter into your JavaScript function. Then, in the success
section of your AJAX call, call your callback function.
Example:
// In HTML <script> tags.
$(document).ready(function () {
$("button#queue").click(function() {
GetMembers(GetGroups(), MemberCallback));
});
});
function GetMembers(userId, callback) {
$.ajax({
//Initialized AJAX properties
url: "/My/Project/Ajax/Page.extension",
data: "{ 'groupId':'" + groupId + "'}",
success: function (result) {
callback(result.d);
}
});
}
function MemberCallback(members) {
// Do your thing here.
}
Disable the button when they click it. Enable it when the ajax routine is complete.
精彩评论