Prevent JavaScript function from running twice (setTimeout) -


i have function runs several seconds use of settimeout. function ran when button 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 user clicks button multiple times, function begins excute multiple times well. have tried prevent occuring using code below, however, 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 take, or how can fix code can accomplish trying do?

your running = false; should inside timeout function, timeout execute asyncronically, running = false; execute before timeout ends

a simple example be

var running = false,     div = document.getelementbyid('response'),     limit = 5,     current = 0;  $('#trigger').click(function () {     if (running === true) {         alert('error: cycle running. aborting.');         running = false;         return false;     }     running = true;     var end = setinterval(function () {         if (current >= limit || running == false) {             running = false;             clearinterval(end);         }         div.innerhtml += 'hello world<br />';         current++;     }, 500);  }); 

jsfiddle example


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -