Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
});
like image 781
neobian Avatar asked Aug 25 '26 18:08

neobian


1 Answers

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);
});
like image 58
Bergi Avatar answered Aug 28 '26 08:08

Bergi