0

button1

<button>button 1</button>
<button>button 2</button>
<button>button 3</button>
<button>button 4</button>

Let's say I have multiple button on a page. When you click on them they turn red. This transformation takes awhile (5-30 seconds).

I implemented an Ajax call that starts the transformation when a button is clicked, it turns the button into red when completed. The button turns red only after the server has responded.

I'm trying to implement a mechanism for ensuring that only one transformation is processed at a time. That is, if the user clicks multiple buttons there is only ever one Ajax call that is being processed at a given time.

I was thinking about implementing a Queue mechanism pushing the ajax call in an array when the user click on a button and run each one recursively. But I don't know how to do it dynamically, meaning, how to tell to my function: 'hey the user add a new item in the queue' please proceed.

I have to connect my array of ajax calls and my function that proceeds ajax calls once at a time. My function should listen to any events occurring in the array.

Any other idea?

Thanks!

Nizar AYARI
  • 203
  • 2
  • 12
  • When you say only one ajax call is processed at a time, does that mean only one request is sent? – nem035 Nov 27 '16 at 02:22
  • Ajax is always aysnc, but you can do is abort the previous request and initiate other. For reference you can have a look at http://stackoverflow.com/questions/19244341/abort-previous-ajax-request-on-new-request – Sumit Surana Nov 27 '16 at 02:24
  • @nem035 yes just on request is sent at a time. For example if the user click on button1 and button2, my magical function should wait the answer for button1 before processing the ajax call for button2. – Nizar AYARI Nov 27 '16 at 02:29
  • @Sumit You can run multiple async function synchronously. The thing is my array has not a fixed length or items, it changes over time. – Nizar AYARI Nov 27 '16 at 02:32

1 Answers1

0

please review this one:

note:

if user click multiple buttons. function will execute the first one. and Put another events in array (queue). when the first event finished, it will execute next event from queue.

var btns = Array.from(document.getElementsByTagName('button')),
    isProcessing = false, queue = [];

function proceed(e){
    if(isProcessing) {
      queue.push(e.target);
      return;
    }
  //start proccesing
  isProcessing = true;
  var ajax = setTimeout(()=> { 
    e.target.classList.add('done');
    isProcessing = false;  
    //processing the queue
    if(queue.length) {
      queue.shift().click();
    }
  },4000);
}

btns.forEach(function(btn){
  btn.addEventListener('click', proceed);
})
button.done {
  color:red;
}
<button>button 1</button>
<button>button 2</button>
<button>button 3</button>
<button>button 4</button>
Community
  • 1
  • 1
RizkiDPrast
  • 1,695
  • 1
  • 14
  • 21