Prevent JavaScript function from running twice (setTimeout)

爷,独闯天下 提交于 2019-12-05 19:27:05
juvian

Your running = false; should be inside timeout function, as timeout will execute asyncronically, the running = false; will execute before your timeout ends

A simple example would be

var running = false,
    div = document.getElementById('response'),
    limit = 5,
    current = 0;

$('#trigger').click(function () {
    if (running === true) {
        alert('Error: The cycle was 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

Assuming you've used addEventListener to attach the click event to the button, you could remove the listener while timeouts are in progress:

function complete() {
    var div = document.getElementById('log'),
        button = this;
    this.removeEventListener('click', complete);
    setTimeout(function(){...});
                 :
    setTimeout(function(){...});
    // If you later want to make the button clickable again, just uncomment the line below:
    // setTimeout(function () {button.addEventListener('click', complete);}, 10000);
}

for stop running timer you have to clear him

        var stopTimer;

        function someFunction() {
            stopTimer= setTimeout(function(){
                console.log("something done");
            }, 3000);
        }

        function stopFunction() {
            clearTimeout(stopTimer);
        }

If you are using jquery it could be more easy.

E.q:

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);

    $( "input[type='button']" ).unbind( "click", complete );
}


$( "input[type='button']" ).bind( "click", complete );

I did some example for you: http://jsfiddle.net/ZA5Ga/

good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!