Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop function from executing again until a certain time has passed

I have a function that runs when you click a button. However I don't want the function to execute again until a certain time has passed. For example, the countdown has finished. If the button is clicked again the function should not run.

$("start").on('click', function() {
  var myTimer;

  function clock() {
    myTimer = setInterval(myClock, 1000);
    var c = 5;

    function myClock() {
      document.getElementById("demo").innerHTML = --c;
      if (c == 0) {
        clearInterval(myTimer);
        alert("Reached zero");
      }
    }
  }
});
like image 440
benj98 Avatar asked Feb 04 '26 19:02

benj98


1 Answers

Firstly remove the clock() function. It serves no purpose given the structure of your code. Secondly, if you're going to use a framework such as jQuery, be consistent with it.

To address the actual issue, store a boolean flag to determine if the time is running or not.

let $demo = $('#demo');

$("#start").on('click', function() {
  let $button = $(this);
  if ($button.data('running'))
    return; // do nothing

  $button.data('running', true);
  let myTimer = setInterval(myClock, 1000);
  let c = 5;
  $demo.html(c);

  function myClock() {
    $("#demo").html(--c);
    if (c == 0) {
      $button.data('running', false);
      clearInterval(myTimer);
      console.log("Reached zero");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>
<div id="demo"></div>
like image 75
Rory McCrossan Avatar answered Feb 07 '26 10:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!