I would like to have a toggle button that runs a function until it's pressed again. I have some code for the toggle:
const backgroundButton = document.getElementById("backgroundButton"); //getting button from HTML
let clickToggle = 0; //defining a veriable used to store the state of the button
backgroundButton.addEventListener("click", function(){
if (clickToggle == 0) {
console.log('button was off');
//start loop
clickToggle = 1;
}
else {
console.log('button was on');
//stop loop
clickToggle = 0;
}
});
But I don't know how to create an infinite loop that does not crash.
You could use setInterval
and clearInterval
. A truly infinite loop would look like this:
while (true) doSomething();
But that is not what anyone wants, as it will block the user interface. Using setTimeout
or setInterval
you allow the event loop to continue to do its work.
I'll assume you want to repeat calling the function doSomething
in this demo:
const backgroundButton = document.getElementById("backgroundButton");
let timer = 0;
const output = document.getElementById("output");
backgroundButton.addEventListener("click", function(){
if (timer == 0) {
console.log('button was off');
//start loop
timer = setInterval(doSomething, 50);
}
else {
console.log('button was on');
//stop loop
clearInterval(timer);
timer = 0;
}
});
function doSomething() {
output.textContent = +output.textContent + 1;
}
<button id="backgroundButton">Start/Stop</button>
<div id="output"></div>