I have this function that runs for several seconds with the use of setTimeout. This function is ran when a button is clicked.
function complete() {
var div = document.getElementById('log');
setTimeout(function(){ div.innerHTML = div.innerHTML + intro[Math.floor(Math.random() * intro.length)] + "<br>"; }, 500);
setTimeout(function(){ div.innerHTML = div.innerHTML + second[Math.floor(Math.random() * second.length)] + "<br>"; }, 2560);
setTimeout(function(){ div.innerHTML = div.innerHTML + third[Math.floor(Math.random() * third.length)] + "<br>"; }, 4860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fourth[Math.floor(Math.random() * fourth.length)] + "<br>"; }, 7860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fifth[Math.floor(Math.random() * fifth.length)] + "<br>"; }, 9640);
}
However, if the user clicks the button multiple times, this function begins to excute multiple times as well. I have tried to prevent this from occuring by using the code below, however, it is not working.
var running;
function complete() {
if (running == true) { alert('error'); }
running = true;
var div = document.getElementById('log');
setTimeout(function(){ div.innerHTML = div.innerHTML + intro[Math.floor(Math.random() * intro.length)] + "<br>"; }, 500);
setTimeout(function(){ div.innerHTML = div.innerHTML + second[Math.floor(Math.random() * second.length)] + "<br>"; }, 2560);
setTimeout(function(){ div.innerHTML = div.innerHTML + third[Math.floor(Math.random() * third.length)] + "<br>"; }, 4860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fourth[Math.floor(Math.random() * fourth.length)] + "<br>"; }, 7860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fifth[Math.floor(Math.random() * fifth.length)] + "<br>"; }, 9640);
running = false;
}
What approach should I take, or how can I fix my code so it can accomplish what I am trying to do?
running = false;at the end of the execution inside your timeouts. You could use a timeout, to run all other timeouts, and at the end of those timeoutes runrunning = false;may do the trick. So 'false' only gets set once in each loop AFTER all the elements run. You can then runclearTimeout()to stop the loops.clearTimeoutto stop them when you first executecomplete(). If you want to clear them all at once, refer to this post for an example.button. How to do it, depends on how have you attached the listener. Can you show, how the listener is attached?returnafter the alert otherwise the rest of the function will still be executed