Wait for the function to end before restarting.

Good morning,

I try to call the same function every time the user clicks a button. Here is what is happening at the moment.

User click button → Call function → takes 1000 ms + to complete (due to animation with jQuery and AJAX calls)

I want every time the user clicks the button, it adds a function to the queue, waits for the previous call to complete, and then starts.

Is it possible?

Sorry if my explanation is a bit confusing.

Thanks Matthew

+4
source share
5 answers

Since functions are objects, they can store properties. You can have your function increment the "queue" property on itself every time its called (the button is pressed), and then at the end of the function check that the queue property itself is> 0, and if so, reduce the queue property one and again call yourself using setTimeout .

+6
source

Recently, I had to do this in my application. The best suggestion I have for you (if you already have your AJAX calls inside a JavaScript function) is to pass a callback function parameter to your JavaScript function. Then, in the success section of your AJAX call, call the 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. } 
0
source

You can add a callback function to the one that does the animation as soon as the animation finishes the callback you call so that you can do what you want.

Below is an example from 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 }); }); 

PS: Morning? It's almost midnight, D

0
source

You can track the global queue / array where you add to the queue every time the user clicks the button, then you need a callback in your function (for example, in the success callback for jQuery) that does the job of checking the queue and calling the following function queue.

0
source

Disable the button when pressed. Turn it on when the ajax procedure is complete.

-1
source

Source: https://habr.com/ru/post/1333108/


All Articles