0

I have a lot of radio buttons on my website. And each of these have the same click handler. Inside the handler I do ajax calls and some more logic which could take some time. So as I said it is the same handler. What actually happens when someone clicks a radio button, so the code inside the handler will be executed, but very fast he presses another radio button and the handler code of the radio button clicked first is not entirely executed. So now again there is a click radio event and again this code starts to execute. How can I prevent that another radio button gets clicked before the handler code is fully executed.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Steffi17
  • 11
  • 2

1 Answers1

0

You can use external variable which contains true if function is during execution

var execution=false;

function action(radio) {
  console.log('try run');

  if(execution) { radio.checked = false; return };
  execution=true;
  
  console.log('execution starts: 5s');  
  setTimeout(()=> {
    console.log('execution ends');    
    execution=false;
  },5000)  
}
<input type="radio" onclick="action(this)">A
<input type="radio" onclick="action(this)">B
<input type="radio" onclick="action(this)">C
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • Thanks. But I do not understand your code. if(execution) { radio.checked = false; return }; If the handler is not finished and another radio button is clicked the handler will be entered again, but according to your code the handler will just be left but I rather look for like a queue. Of course it should be handled after the first radio button is finished – Steffi17 Nov 07 '19 at 21:56
  • You can create queue (as array of boolean) and instead execute `return` statement (like in my `if`) - put `true` value to that array. Then inside setTimeout you can use loop to check if any true value is set (if yes then set it to false and execude right code) – Kamil Kiełczewski Nov 07 '19 at 22:02
  • @Steffi17 other wise you can use execution.abort(). method before your radio click event execution. i hope it's work for you. please ref url https://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery – chandu komati Nov 08 '19 at 03:45