Reputation: 3986
I've been doing a lot of searching and don't think I can find what I am looking for.
I have a system similar to how twitter works where you need to add (or follow in Twitter) multiple people at a click of a button.
So for example every time I click an "Add" button below, it makes an AJAX request to add them to the database.
<ul>
<li>Ben <a href="#" onclick="return addPerson(1);">Add</a></li>
<li>Sarah <a href="#" onclick="return addPerson(2);">Add</a></li>
<li>Chantelle <a href="#" onclick="return addPerson(3);">Add</a></li>
<li>Alan <a href="#" onclick="return addPerson(4);">Add</a></li>
</ul>
Now if I click the add button for each person, one after another, I don't think queuing one ajax request for each person would be a good use of resources. Plus it would be slow.
What I'm thinking is maybe a delay or something along those lines after I click each "Add" button. So it records all the ID's of the people I click, and sends one ajax request for all the people clicked.
Is there an existing script or can you recommend how I could do this?
Upvotes: 2
Views: 259
Reputation: 1749
Would something like this do the trick?
var sendDelay;
var peopleToSend = [];
addPerson = function(id) {
if (sendDelay!=null) {
clearTimeout(sendDelay); // Clear timeout
}
sendDelay=setTimeout(addPersonDelayComplete,2000); // Reset timeout
peopleToSend.push(id); // Add person to array
}
addPersonDelayComplete = function() {
// Send the people in peopleToSend in a single ajax call here
peopleToSend.length = 0; // Reset the array
}
Upvotes: 3