elad.chen
elad.chen

Reputation: 2425

clearInterval is not clearing

Take a look at the function below, It purpose is to change the button text to "Abort", "Abort 0", "Abort 1" and so on.

Once the counter reaches 10 another function should be executed, but if the button is clicked, the counter should stop, and the button text should return to it's original value ("Sync DB").

It seems I'm trying to clear out the interval in a wrong way.

Any assistance will be appreciated.

function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }

sync_db_btn.innerHTML = "Abort"
var i = 0;
sync_db_btn.addEventListener("click", function() { sync_database(true) } );

var x = setInterval(function() {
    if (abort == true) {
        clearInterval(x);
    }

    if (i < 10) {
        sync_db_btn.innerHTML = "Abort " + i++; 
    }
}, 1000);
}

Upvotes: 0

Views: 165

Answers (2)

Teemu
Teemu

Reputation: 23396

I think you need something like this:

var sync_db_btn = document.getElementById('but'),
    abortSync = -1,
    interval,
    sync_database = function () {
        var i = 0;
        abortSync *= -1;
        if (abortSync < 0) {
            sync_db_btn.innerHTML = 'Sync DB';
            clearInterval(interval);
            return false;
        }
        sync_db_btn.innerHTML = 'Abort';
        interval = setInterval(function () {
            if (i < 10) {
                sync_db_btn.innerHTML = 'Abort ' + i++;
            } else {
                sync_db_btn.innerHTML = 'Sync DB';
                clearInterval(interval);
                abortSync = -1;
            }
        }, 1000);
    };
sync_db_btn.addEventListener('click', sync_database);

A live demo at jsFiddle.

Upvotes: 0

php_nub_qq
php_nub_qq

Reputation: 16015

var x;

sync_db_btn.addEventListener("click", function() {
    sync_database(true); 
    clearInterval(x); 
} );

function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }

    sync_db_btn.innerHTML = "Abort"
    var i = 0;

    x = setInterval(function() {    
        if (i < 10) {
            sync_db_btn.innerHTML = "Abort " + i++; 
        }
    }, 1000);
}

Upvotes: 1

Related Questions