I have several buttons on my page which are either "start timer" buttons, or "stop timer" buttons, which run startTimer and stopTimer functions respectively.
During the startTimer function, the button's onclick changes from startTimer to stopTimer, and vice versa.
At the moment, once clicked, the button runs both functions one after the other perpetually.
I want it to run the function, then stop ready for the button to be clicked again and the opposite function to be run.
One approach I have been exploring is disabling the button while it's running, having the functions check for an enabled button, running the function, then attempting to create an event to reenable it. It's the last bit I'm struggling with.
function startTimer(project) {
var url = document.URL + '?timer=start&id=' + project;
var buttonid = 'button' + project;
var button = document.getElementById(buttonid);
var stopText = 'stopTimer(' + project + ')';
if(button.disabled == false){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send();
var result = xmlhttp.responseText;
if(result == 'ok'){
button.disabled = true;
button.setAttribute("class","btn btn-danger btn-mini");
button.value = "Stop Timer";
button.setAttribute("onclick", stopTimer(project));
}
else{
alert("I couldn't start the timer.");
}
}
}
function stopTimer(project) {
var url = document.URL + '?timer=stop&id=' + project;
var buttonid = 'button' + project;
var button = document.getElementById(buttonid);
var startText = 'startTimer(' + project + ')';
if(button.disabled == false){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send();
var result = xmlhttp.responseText;
if(result == 'ok'){
button.disabled = true;
button.setAttribute("class","btn btn-sucess btn-mini");
button.value = "Start Timer";
button.setAttribute("onclick", startTimer(project));
}
else{
alert("I couldn't stop the timer.");
}
}
HTML/PHP:
<?php if(in_array($project[0], $started)){ ?>
<td>
<input type="button" class="btn btn-danger btn-mini" value="Stop Timer" onClick="stopTimer(<?php echo $project[0]; ?>)" id="button<?php echo $project[0]; ?>" />
</td>
<?php } else { ?>
<td>
<input type="button" class="btn btn-success btn-mini" value="Start Timer" onClick="startTimer(<?php echo $project[0]; ?>)" id="button<?php echo $project[0]; ?>" />
</td>
<?php } ?>
I would recommend creating one function toggleTimer, and binding the button's click to that. So, instead of futzing with the button's click attribute, you would just need to adjust the url for your request accordingly.
/copypasta