neobian
neobian

Reputation: 41

Extend timeout function when button is clicked

This piece of code works, but I am trying to get the timeout function to reset to '0' every time the button is clicked.

var running = false,
    count = 0,
    run_for = 700;


var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};

$('button').click(function() {
    if (running) {
    count++;


    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        setTimeout(end_counter, run_for);
    }
});

Upvotes: 3

Views: 2559

Answers (2)

dxritchie
dxritchie

Reputation: 138

var running = false,
    count = 0,
    run_for = 700;

var timer;

var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};

$('button').click(function() {
    clearTimeout(timer);
    if (running) {
        count++;
        timer = setTimeout(end_counter, run_for);
    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        timer = setTimeout(end_counter, run_for);
    }
});

Set timer to a variable - then clear it on click and restart it after count.

Upvotes: 0

Bergi
Bergi

Reputation: 664528

Just cancel and restart it:

var timerId,
    count = 0;
function end_counter() {
    $("#status").text("Not Running");
    alert(count);
    count = 0;
}
$('button').click(function() {
    $("#status").text("Running");
    count++;
    clearTimeout(timerId);
    timerId = setTimeout(end_counter, 700);
});

Upvotes: 7

Related Questions