Reputation: 45
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");
}
}
}
});
Upvotes: 3
Views: 145
Reputation: 337713
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>
Upvotes: 1